--[[
  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 MCanReceive = require('common.block').getBlock(globals, cpu)
  if not static[cpu] then
    static[cpu] = {
      numInstances = 0,
      instances = {},
      finalized = false,
    }
  end
  MCanReceive.instance = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1

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

  function MCanReceive:checkMaskParameters()

    self.mcanUnitAsChar = U.comboAsChar(Block.Mask.MCanUnit)

    -- 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.msgWidth = CAN_CONFIG.getBlockFrameLength(true)
  end

  function MCanReceive:p_getDirectFeedthroughCode()
    local Require = ResourceList:new()
    local Declarations = U.CodeLines: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', 'mcanUnitAsChar')

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

    self.mbox = self.mcanObj:getRxMailbox()

    self.mcanObj:setupRxMailbox(self.mbox, {
      canId = self.canId,
      isExtId = self.isExtId,
      width = self.msgWidth,
      dlc = CAN_CONFIG.calcDLC(self.msgWidth),
    })

    local outSignal = Block:OutputSignal()
    local outIdx = U.enum({'d', 'v', 'f'})

    local outputCode = [[{
      static unsigned char data[%(width)d] = {%(dataInitialValues)s};
      static bool firstRun = true;
      uint16_t flags = 0;
      %(outSigNewDataFlag)s = PLXHAL_MCAN_getMessage(%(handle)d, %(mbox)d, &data[0], %(width)d, &flags);
      if(firstRun || %(outSigNewDataFlag)s){
        memcpy(&%(outSigData)s, &data[0], %(width)d*sizeof(uint8_t));
        %(outSigErrorActive)s = ((flags & 1) != 0);
        %(outSigFdFormat)s = ((flags & 2) != 0);
        %(outSigBitRateSwitchingEn)s = ((flags & 4) != 0);
        firstRun = false;
      }}]] % {
      handle = self.mcanInstance,
      mbox = self.mbox,
      width = self.msgWidth,
      dataInitialValues = U.repeatValueString('0xFF', self.msgWidth),
      outSigData = outSignal[outIdx.d][1],
      outSigNewDataFlag = outSignal[outIdx.v][1],
      outSigErrorActive = outSignal[outIdx.f][1],         -- error state
      outSigFdFormat = outSignal[outIdx.f][2],            -- classic or FD format
      outSigBitRateSwitchingEn = outSignal[outIdx.f][3],  -- bitRateSwitching
    }
    OutputCode:append(outputCode)

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

  function MCanReceive: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 MCanReceive
end

return Module
