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

local static = {}
local Module = {}

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

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

  function MCanTransmit:checkMaskParameters()
    self.mcanUnitAsInt = Block.Mask.MCanUnit - 1
    self.mcanUnitAsChar = string.char(65 + self.mcanUnitAsInt)

    -- 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]

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

    self.bitRateSwitchingEnabled = U.comboEnabled(
      Block.Mask.EnableBitRateSwitching)

    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 MCanTransmit: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
    self.mcanObj = self:getBlockInstanceWithMatchingParameter('mcan', 'mcanUnitAsInt')

    if not self.mcanObj then
      -- create new CAN object
      self.mcanObj = self:makeBlock('mcan', self.cpu)
      self.mcanObj:createImplicit(self.mcanUnitAsInt)
    end
    self.mcanInstance = self.mcanObj:getObjIndex()

    -- setup mailbox
    self.mbox = self.mcanObj:getTxMailbox()
    self.dlc = CAN_CONFIG.calcDLC(self.width)

    self.mcanObj:setupTxMailbox(self.mbox, {
      canId = self.canId,
      isExtId = self.isExtId,
      width = self.width,
      dlc = self.dlc,
      brsEnabled = self.bitRateSwitchingEnabled,
    })

    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_MCAN_putMessage(%d, %d, canData, %d);' %
       {self.mcanInstance, 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,
      })
    else
      error('Unhandled combo option.')
    end

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

  function MCanTransmit:p_getNonDirectFeedthroughCode()
    if not self.mcanObj:canPortConfigured() then
      U.error(
        'Please add CAN Port component for MCAN %s.' % {self.mcanUnitAsChar})
    end
    return {}
  end

  -- No finalize() actions for this block
  
  return MCanTransmit
end

return Module
