--[[
  Copyright (c) 2022 by Plexim GmbH
  All rights reserved.

  A free license is granted to anyone to use this software for any legal
  non safety-critical purpose, including commercial applications, provided
  that:
  1) IT IS NOT USED TO DIRECTLY OR INDIRECTLY COMPETE WITH PLEXIM, and
  2) THIS COPYRIGHT NOTICE IS PRESERVED in its entirety.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
--]]--
local Module = {}
local U = require('common.utils')

local static = {}

function Module.getBlock(globals, cpu)

  local IpcTriggerTransmit = require('common.block').getBlock(globals, cpu)
  if not static[cpu] then
    static[cpu] = {
      numInstances = 0,
      instances = {},
      finalized = false,
    }
  end
  IpcTriggerTransmit["instance"] = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1

  function IpcTriggerTransmit:checkMaskParameters()

  end

  function IpcTriggerTransmit:createImplicitIpcTrigTx(params, req)
    table.insert(static[self.cpu].instances, self.bid)
    self.cpuConfig = {}
    self.cpuConfig['local_cpu'] = self.cpu + 1
    self.cpuConfig['remote_cpu'] = params.remoteCpu + 1
  end

  function IpcTriggerTransmit:p_getDirectFeedthroughCode()
    local Require = ResourceList:new()
    local InitCode = U.CodeLines:new()

    table.insert(static[self.cpu].instances, self.bid)

    self.cpuConfig = {}

    -- only allow a single trigger transmit block for now
    if static[self.cpu].numInstances ~= 1 then
      U.error("The use of multiple IPC TX Trigger blocks is not allowed.")
    end

    if Target.Variables.targetCore == nil then
      U.error("IPC trigger transmit block can only be used on multicore targets.")
    else
      self.cpu['local_cpu'] = self.cpu
      if (self.cpuConfig['local_cpu'] ~= nil) and (self.cpuConfig['local_cpu'] == 1) then
        self.cpuConfig['remote_cpu'] = 2
      else
        self.cpuConfig['remote_cpu'] = 1
      end
    end

    return {
      InitCode = InitCode,
      Require = Require,
      UserData = {bid = self:getId()}
    }
  end

  function IpcTriggerTransmit:p_getNonDirectFeedthroughCode()
    local trig = Block.InputSignal[1][1]

    -- verify proper connection of trigger point
    trig = trig:gsub("%s+", "") -- remove whitespace
    if trig:sub(1, #"{modtrig") ~= "{modtrig" then
      U.error("This block must be connected to a 'Task trigger' port.")
    end
    
    self['trigExpression'] = trig
    
    return {}
  end

  function IpcTriggerTransmit:setSinkForTriggerSource(sink)
    if sink ~= nil then
      -- should never happen (block has no trigger output)
    end

    -- top of chain
    if self['trigExpression'] ~= nil then
      local trig = eval(self['trigExpression'])['modtrig']
      if trig['bid'] ~= nil then
        globals.instances[trig['bid']]:setSinkForTriggerSource({
          type = 'modtrig',
          bid = self.bid
        })
      end
    end
  end

  function IpcTriggerTransmit:propagateTriggerSampleTime(ts)
    if ts ~= nil then
      self['ts'] = ts
      self:logLine('Task trigger sample time for %s (%i) propagated to: %f.' %
                       {self.blockType, self.bid, ts})
    end
  end

  function IpcTriggerTransmit:getTriggerSampleTime()
    return self['ts']
  end

  function IpcTriggerTransmit:finalizeThis(c)
  end

  function IpcTriggerTransmit:finalize(c)
    if static[self.cpu].finalized then
      return
    end

    for _, bid in ipairs(static[self.cpu].instances) do
      local ipc = globals.instances[bid]
      if ipc:getCpu() == self.cpu then
        ipc:finalizeThis(c)
      end
    end

    static[self.cpu].finalized = true
  end

  return IpcTriggerTransmit
end

return Module
