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

local static = {}
local Module = {}

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

  function CanPort:checkMaskParameters()

    self.canUnitAsChar = U.comboAsChar(Block.Mask.CanUnit)

    self.mask = {
      gpio = U.enforceMask(U.isPinPair, 'Gpio'),
      autoBusOn = U.comboEnabled(Block.Mask.AutoBusOn),
      baudRate = U.enforceMask(U.isIntScalarInClosedInterval, 
                               'BaudRate', 1, 1e6),
      samplePoint = U.enforceMask('isIntScalarInOpenIntervalPercent', 
                                  'BitSamplePoint', 50, 100) / 100,
    }

    if U.comboEnabled(Block.Mask.AdvancedBitRateConf) then
      self.mask.opt_bitLengthTq = U.enforceMask(U.isPositiveIntScalar, 
                                                'BitInTq')
      self.mask.opt_sjwTq = U.enforceMask(U.isPositiveIntScalar, 'SjwInTq')
    end

  end

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

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

    local canResourceStr = 'CAN %s' % {self.canUnitAsChar}
    if not self:checkResourceExists(canResourceStr) then
      U.error(canResourceStr..' is not available on this target.')
    end
    Require:add(canResourceStr)

    -- 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:createImplicit(self.canUnitAsChar)
    end

    self.canInstance = self.canObj:getObjIndex()

    self.canObj:configureCAN(self.mask, Require)
    
    local inIdx = U.enum({'en'})
    local outIdx = U.enum({'on', 'ea'})

    OutputCode:append([[
      {
        static bool lastBusOn = false;
        bool busOn = %(busOnInput)s;
        if(!busOn){
          PLXHAL_CAN_setBusOn(%(canInstance)d, false);
        } else if (!lastBusOn){
          PLXHAL_CAN_setBusOn(%(canInstance)d, true);
        }
        lastBusOn = busOn;
      }]] % {
      canInstance = self.canInstance,
      busOnInput = Block.InputSignal[inIdx.en][1],
    })
    
    OutputSignal[outIdx.on] = {'PLXHAL_CAN_getIsBusOn(%d)' % {self.canInstance}}
    OutputSignal[outIdx.ea] = {'PLXHAL_CAN_getIsErrorActive(%d)' % {self.canInstance}}

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

  function CanPort:p_getNonDirectFeedthroughCode()
    return {}
  end

  -- No finalize() actions for this block

  return CanPort
end

return Module
