--    ======================
--    Description
--    ======================
--
--    logic takes input, and settings and do input & setting bitwise operator
--    and result, casted to boolean,  is written to the output.
--
--    Input to wartość z zakodowanym ze stanem bitowym. Na podstawie ustawienia identyfikującego bita lub bity (setting.bit.mask),
--    właściwa wartość stanu bitowego jest wpisywana do output.
--
--    ======================
--    Parameters
--    ======================
--
--    SubLogic supports following variables:
--
--    input                                   - wartość wejściowa, liczba z zakodowanymi wartościami bitowymi
--
--    output                                  - wartość wyjściowa 0 lub 1
--
--    setting.bit.mask                        - maska identyfikująca bit/bity który ma być sprawdzany z input:
--                                                setting.bit.mask = 1     -> 0000000000000001 - bit 0
--                                                setting.bit.mask = 2     -> 0000000000000010 - bit 1
--                                                setting.bit.mask = 4     -> 0000000000000100 - bit 2
--                                                setting.bit.mask = 8     -> 0000000000001000 - bit 3
--                                                setting.bit.mask = 16    -> 0000000000010000 - bit 4
--                                                setting.bit.mask = 32    -> 0000000000100000 - bit 5
--                                                setting.bit.mask = 64    -> 0000000001000000 - bit 6
--                                                setting.bit.mask = 128   -> 0000000010000000 - bit 7
--                                                setting.bit.mask = 256   -> 0000000100000000 - bit 8
--                                                setting.bit.mask = 512   -> 0000001000000000 - bit 9
--                                                setting.bit.mask = 1024  -> 0000010000000000 - bit 10
--                                                setting.bit.mask = 2048  -> 0000100000000000 - bit 11
--                                                setting.bit.mask = 4096  -> 0001000000000000 - bit 12
--                                                setting.bit.mask = 8192  -> 0010000000000000 - bit 13
--                                                setting.bit.mask = 16384 -> 0100000000000000 - bit 14
--                                                setting.bit.mask = 32768 -> 1000000000000000 - bit 15
--
--    ======================
--    mandatory variables
--    ======================
--
--    Logic expects following mandatory variables:
--
--    reload.trigger                          - causes reloading lua script
--
--    memcnt                                  - current amount of memory used by lua in bytes
--
--    Logic expects following kv settings:
--
--    LuaScriptPath                           - path to the lua script - must be absolute
--
--    ======================
--    ChangeLog
--    ======================
--
--    2022-02-19 ver 0.0.3.3
--
--    # komentarze, reorganizacja nazewnictwa zmiennych
--
--    2017-06-07 ver 0.0.2.2
--
--    # obsługa automatycznego build'a
--    # opis logiki
--
--    2017-06-07 ver 0.0.1.1
--
--    # zmiana nazw inputów
--
--    2017-03-17 ver 0.0.0.0
--
--    # First release
--
-- user can use some functions provided by ibmanager.

-- ibmanager provides following functions to use:
--
-- function returns value of required ibmanager variable
-- @param fullName - string - variable name - name of variable of which value must be returned, for example "rs.0.id.255.input.t.0.value"
-- @return         - string or integer - variable value or "nil" if variable not exist or is not readable
--
-- getValue(fullName)


-- function set value of given ibmanager variable
-- @param fullName - string - variable name - name of variable of which value we want to set, for example "rs.0.id.255.input.t.0.value"
-- @param value    - string, int or boolean - value to set
-- @return         - nothing
--
-- setValue(fullName, value)


-- function returns value of required ibmanager variable
-- @param key      - placed in xml logic configuration file:
--                   * as attribute: Name, in Var, RemoteVar and ImportVar elements in the case of stand alone variables
--                   * as concatenation of two attributes: ListName.Postfix in VarListItem, RemoteVarListItem and ImportVarListItem elements
--                     in the case of variables that are placed in lists
-- @return         - string or integer - variable value or "nil" if variable not exist or is not readable
--
-- getLogicValue(key)


-- function set value of given ibmanager variable
-- @param key      - placed in xml logic configuration file:
--                   * as attribute: Name, in Var, RemoteVar and ImportVar elements in the case of stand alone variables
--                   * as concatenation of two attributes: ListName.Postfix in VarListItem, RemoteVarListItem and ImportVarListItem elements
--                     in the case of variables that are placed in lists
-- @param value    - string, int or boolean - value to set
-- @return         - nothing
--
-- setLogicValue(key, value)

-- function returns two sections of kvsettings from xml configuration file
-- returned value is two element table, each of these elements is table too.
-- indices of returned table are strings and equal "instance" and "global"
-- values of returned tables are tables and contain KVsettings for applicable section.
-- nested tables have form key = value, where key is index in nested table and value is value.
-- example: {"instance" = {"ikey1" = "ivalue1", "ikey2" = "gvalue2"}, "global" = {"gkey1" = "gvalue1", "gkey2" = "gvalue2", "gkey3" = "gvalue3"}}
-- @return          - two dimensional array - kvsettings for global and instance sections
-- getKvSettings()


-- function schedules alert to send.
-- rules are defined in separated alert configuration files and are described in ibmanager instruction manual
-- @param id - alert identifier - must be defined in current logic configuration file in section: <Alert Id="any_identifier" ...
-- scheduleAlert(id)

-- function cancels alert sending, if was previously scheduled. if not then only wakes up alerts handling thread, so if there is no need to call this function, then do not call it.
-- rules are defined in separated alert configuration files and are described in ibmanager instruction manual
-- @param id - alert identifier - must be defined in current logic configuration file in section: <Alert Id="any_identifier" ...
-- cancelAlert(name)

-- function returns table, containing Variables that belongs to required list.
-- @param listName - Name attribute of VarList, RemoteVarList or ImportVarList elemetnst in configurationfile
-- @return array of key-value pairs. Key - variable postfix, Value - Variable value
-- getVarList(listName)

-- function returns monotonic system clock value, that elapsed since specific epoch
-- returned time is expressed in milliseconds.
-- getClock()

-- function logs message to file, if defined in configuration file log level is less than passed to this function
-- @param logLevel - one of:
--        LogLevel.TraceLo
--        LogLevel.Trace
--        LogLevel.TraceHi
--        LogLevel.DebugLo
--        LogLevel.Debug
--        LogLevel.DebugHi
--        LogLevel.Info
--        LogLevel.Notice
--        LogLevel.Warning
--        LogLevel.Error
--        LogLevel.Critical
-- @param logMessage - string to log
-- log(logLevel, logMessage)


-- ibmanager provides following global variables:

-- logic type, (in this case it will always be "Lua") - the same as in logic configuration file in section: <Logic Type="Lua" ...
-- LOGIC_TYPE

-- logic version, the same as in logic configuration file in section: <Logic ... Version="x.y.z" ...
-- LOGIC_VERSION

-- logic sub-type, the same as in logic configuration file in section: <Logic ... SubType="Hysteresis" ...
-- LOGIC_SUBTYPE

-- logic sub-version, the same as in logic configuration file in section: <Logic ... SubVersion="x.y.z" ...
-- LOGIC_SUBVERSION

-- logic instance name - the same as in logic configuration file, in section: <Instance Name="0">
-- LOGIC_INSTANCE_NAME

-- add script directory to package path
package.path = package.path .. ";/ibsystem/ibmanager/logic/lua/utils/?.lua";
package.path = package.path .. ";/work/insbud/iblogics/Lua/Scripts/utils/?.lua";


-- ---------------------------------------------------------------------------------------------------------
-- global - enums
-- ---------------------------------------------------------------------------------------------------------
MIN_POSTFIX_VALUE   = 0;
MAX_POSTFIX_VALUE   = 63;

AUTO_MODE = 0;
MANUAL_MODE = 1;

-- ---------------------------------------------------------------------------------------------------------
-- 
-- ---------------------------------------------------------------------------------------------------------


-- logic class
Logic = {};

Logic.__index = Logic;

-- ---------------------------------------------------------------------------------------------------------
-- 
-- ---------------------------------------------------------------------------------------------------------

function Logic.create()

  --our new object
  local logic         = {};  
  setmetatable(logic, Logic);
  
  --our object fields initialization
  logic.items                   = {}

  -- adding items and filling settings and its value
  local inputListName = "input.values";
  
  local lst = getVarList(inputListName);
  
  if lst ~= nil then
    for postfix, _ in pairs(lst) do
    
      local postfixNumber = tonumber(postfix);
      
      --checking postfix requirements
      if postfixNumber == nil then
        error ("element postfix  " .. postfix .. " in list " .. inputListName .. "is not a number");
      end
      
      if (postfixNumber < MIN_POSTFIX_VALUE or postfixNumber > MAX_POSTFIX_VALUE) then
        error ("element postfix  " .. postfix .. " in list " .. inputListName .. "must be between " .. MIN_POSTFIX_VALUE .. " and " .. MAX_POSTFIX_VALUE);
      end
      
      -- building logic input variable name
      
      local iVar = inputListName .. "." .. postfix;
      
      -- add item, key - input variable name, value - bit position
      logic.items[iVar] = postfixNumber;
      --print("postfixNumber: " .. postfixNumber .. ", iVar: " .. iVar .. ");
    end
    
  end
  
  
  return logic;
  
end

-- ---------------------------------------------------------------------------------------------------------
-- 
-- ---------------------------------------------------------------------------------------------------------

function Logic:call()

  local outputValue   = 0;
  local mode          = getLogicValue("setting.mode");
  local manualValue   = mode == MANUAL_MODE and getLogicValue("setting.manual.value") or nil;
 
  if (manualValue ~= nil) then
  
    outputValue = manualValue;
  
  else
  
    for varName, bitPos in pairs(self.items) do
  
      local input = getLogicValue(varName);
      local bitMask = 1 << bitPos;
      
      if (input == 0) then
        outputValue = outputValue & ~bitMask;
      else
        outputValue = outputValue | bitMask;
      end

    end
  
  end

  setLogicValue("output.value", outputValue);
  
end

-- ---------------------------------------------------------------------------------------------------------

-- main logic state object
g_logic = nil;

SUPPORTED_SUBLOGIC_TYPE = "B2bm";
SUPPORTED_SUBLOGIC_VERSION = "0.0.0";
g_versionChecked = false;

-- ---------------------------------------------------------------------------------------------------------

-- entry point to the logic
-- @param firstCall - tells if logic is called first time
-- @return        - nothing
function onLogicCall(firstCall)

  if not g_versionChecked then
    -- checking sublogic type and sublogic version
    if LOGIC_SUBTYPE ~= SUPPORTED_SUBLOGIC_TYPE then
      error("Wrong logic sub-type. expected " .. SUPPORTED_SUBLOGIC_TYPE .. " but used " .. LOGIC_SUBTYPE);
    end
    local versionWithoutBuild = string.match(LOGIC_SUBVERSION, "[0-9]+%.[0-9]+%.[0-9]+");
    if versionWithoutBuild ~= SUPPORTED_SUBLOGIC_VERSION then
      error("Wrong logic sub-version. expected " .. SUPPORTED_SUBLOGIC_VERSION .. " but used " .. LOGIC_SUBVERSION);
    end
    g_versionChecked = true;
  end
  
  if g_logic == nil then
  
    g_logic = Logic.create();

  end
  
  
  g_logic:call()
  


end

-- ---------------------------------------------------------------------------------------------------------
