--[[
  Copyright (c) 2021 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 CAN_CONFIG = require('common.can_config')
local U = require('common.utils')

local static = {}
local Module = {}

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

  local inIdx = U.enum({'d', 'trigger', 'id'})

  function CanTransmit:checkMaskParameters()
    self.canUnitAsChar = U.comboAsChar(Block.Mask.CanUnit)

    -- Figure out the canId
    self.canId = CAN_CONFIG.getBlockCanId(inIdx.id)

    -- Determine the Frame Format (extended or regular)
    self.isExtId = CAN_CONFIG.isExtId(self.canId)


    self.width = #Block.InputSignal[inIdx.d]
    if (self.width > 8) then
      U.error('CAN message length must not exceed 8 bytes.')
    end

    -- require data to be uint8
    U.enforcePort('d', U.portInputTypeIs, inIdx.d, 'uint8')

    self.cbx_execution = U.enforceMask_newComboBox(
      'Execution',
      {'Regular', 'Triggered'})


    if self.cbx_execution.equals('Triggered') then
      self.opt_cbx_triggerType = U.enforceMask_newComboBox(
        'TriggerType',
        {'Rising', 'Falling', 'Either'})
    end

  end

  function CanTransmit:p_getDirectFeedthroughCode()
    local Require = ResourceList:new()
    local Declarations = U.CodeLines:new()
    local InitCode = U.CodeLines:new()
    local OutputSignal = StringList:new()
    local OutputCode = U.CodeLines:new()

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

 

    -- see if a CAN object as already been created on the same CPU
    self.canObj = self:getBlockInstanceWithMatchingParameter('can', 'canUnitAsChar')

    if not self.canObj then
      -- create new CAN object
      self.canObj = self:makeBlock('can', self.cpu)
      self.canObj:createImplicitCan(self.canUnitAsChar)
    end
    self.canInstance = self.canObj:getObjIndex()

    -- setup mailbox
    self.mbox = self.canObj:getMailbox()

    self.canObj:setupTxMailbox(self.mbox, {
      canId = self.canId,
      isExtId = self.isExtId,
      width = self.width,
    })


    local msgDataList = {}
    for idx = 1, self.width do
      table.insert(msgDataList, Block.InputSignal[inIdx.d][idx])
    end
    local msgDataStr = table.concat(msgDataList, ', ')

    local putMessageCode =
       'PLXHAL_CAN_putMessage(%d, %d, canData, %d);' %
       {self.canInstance, self.mbox, self.width}
    
    if self.cbx_execution.equals('Regular') then
      OutputCode:append([[
        {
          unsigned char canData[] = {%(msgDataStr)s};
          %(putMessageCode)s
        }]] % {
        msgDataStr = msgDataStr,
        putMessageCode = putMessageCode,
      })
    elseif self.cbx_execution.equals('Triggered') then
      local triggerConditional
      if self.opt_cbx_triggerType.equals('Rising') then
        triggerConditional = '!canLastTriggerValue && canTriggerValue'
      elseif self.opt_cbx_triggerType.equals('Falling') then
        triggerConditional = 'canLastTriggerValue && !canTriggerValue'
      else -- Either
        triggerConditional = 'canLastTriggerValue != canTriggerValue'
      end

      OutputCode:append([[
        {
          unsigned char canData[] = {%(msgDataStr)s};
          static unsigned char canLastTriggerValue = 0;
          int canTriggerValue = !!(%(trigVal)s);

          if (%(triggered)s) {
            %(putMessageCode)s
          }
          canLastTriggerValue = canTriggerValue;
        }]] % {
        msgDataStr = msgDataStr,
        trigVal = Block.InputSignal[inIdx.trigger][1],
        triggered = triggerConditional,
        putMessageCode = putMessageCode,
      })
    end

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

  function CanTransmit:p_getNonDirectFeedthroughCode()
    if not self.canObj:canPortConfigured() then
      U.error('Please add CAN Port component for CAN %s.' % {self.canUnitAsChar})
    end
    return {}
  end

  -- No finalize() actions for this block.

  return CanTransmit
end

return Module
