--[[
  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 Module = {}
local U = require('common.utils')

--[[
TODO:
- handle background task
- figure out how to trigger on-time init task
- does it make sense to allow tasks that are periodically triggered by s/w?
- add resource management
]]

local static = {}

function Module.getBlock(globals, cpu)

  local Cla = require('common.block').getBlock(globals, cpu)
  if not static[cpu] then
    static[cpu] = {
      numInstances = 0,
      instances = {},
      finalized = false,
    }
  end
  Cla["instance"] = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1
  
  
  function Cla:checkMaskParameters()
    if self:targetMatches({'2806x', '2833x'}) then
      U.error('CLA is not supported for this chip.')
    end
  end
  
  function Cla:p_getDirectFeedthroughCode()
    local Require = ResourceList:new()
    local OutputSignal = StringList:new()
    local TriggerOutputSignal = StringList:new()
    
    table.insert(static[self.cpu].instances, self.bid)
    
    local taskNum = Block.Mask.ClaTask
    local isBackgroundTask = false
    if (Block.Mask.ClaTaskTrig == 2) and (Block.Mask.ClaTaskType == 2) then
      isBackgroundTask = true
      taskNum = 8
    end
    
    -- TODO: resource management - background is task 8
    

    local taskParams = {
      Declarations = U.CodeLines:new(),
      Code = U.CodeLines:new(),
    }
    
    taskParams.Declarations:append(Block.Mask.ClaTaskDeclarations)
    taskParams.Code:append(Block.Mask.ClaTaskSource)

    self.task = {
      is_background = isBackgroundTask,
      num = taskNum,
      declarations = taskParams.Declarations,
      code = taskParams.Code
    }
    
    TriggerOutputSignal:append("{modtrig = {bid = %i}}" % {Cla:getId()})
    
    return {
      OutputSignal = {TriggerOutputSignal},
      Require = Require,
      UserData = {bid = self:getId()}
    }
  end
  
  function Cla:p_getNonDirectFeedthroughCode()
    local trig = Block.InputSignal[1][1]
    
    if Block.Mask.ClaTaskTrig == 1 then
      -- hardware trigger
      if string.find(trig, "UNCONNECTED") then
        U.error('Trigger input port can not be left unconnected.')
      end
      -- 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
    end

    return {}
  end
  
  function Cla:setSinkForTriggerSource(sink)
    if self['trigExpression'] == nil then
      -- no triggering
      return
    end
    
    local trig = eval(self['trigExpression'])['modtrig']
    local triggerBlock = globals.instances[trig['bid']]
    self['trig'] = triggerBlock

    if sink ~= nil then
      self:logLine('Cla task connected to %s of %d.' % {sink.type, sink.bid})
      if self[sink.type] == nil then
        self[sink.type] = {}
      end
      table.insert(self[sink.type], globals.instances[sink.bid])
    end

    if self.downstreamConnectionsPropagated == nil then
      -- top of chain
      if self['trig'] ~= nil then
        self['trig']:setSinkForTriggerSource({type = 'modtrig', bid = self.bid})
      end
      self.downstreamConnectionsPropagated = true;
    end
  end

  function Cla:propagateTriggerSampleTime(ts)
    if ts ~= nil then
      self:logLine('Cla trigger sample time propagated to %f.' % {ts})
      self['ts'] = ts
      if self['modtrig'] ~= nil then
        for _, b in ipairs(self['modtrig']) do
          local f = b:propagateTriggerSampleTime(ts)
        end
      end
    end
  end

  function Cla:getTriggerSampleTime()
    return self['ts']
  end
  
  function Cla:generateTaskTriggerIsrCode(f)
    local itFunction
    if self.trig:blockMatches('adc') then
      local adcUnitAsChar = self.trig:getParameter('adcUnitAsChar')
      itFunction = [[
        interrupt void %(base_name)s_baseTaskInterrupt(void)
        {
          PieCtrlRegs.PIEACK.bit.ACK11 = 1;
          %(adc_reg)s.ADCINTFLGCLR.bit.ADCINT1 = 1;
          IER |= M_INT11;
          DISPR_dispatch();
        }
      ]] % {
        base_name = Target.Variables.BASE_NAME,
        adc_reg = 'Adc%sRegs' % {string.lower(adcUnitAsChar)},
      }
    elseif self.trig:blockMatches('epwm_basic')
    or     self.trig:blockMatches('epwm_var')
    or     self.trig:blockMatches('epwm_basic_pcc')
    or     self.trig:blockMatches('epwm_var_pcc') then
      itFunction = [[
        interrupt void %(base_name)s_baseTaskInterrupt(void)
        {
          PieCtrlRegs.PIEACK.bit.ACK11 = 1;
          %(epwm_reg)s.ETCLR.bit.INT = 1;
          IER |= M_INT11;
          DISPR_dispatch();
        }
      ]] % {
        base_name = Target.Variables.BASE_NAME,
        epwm_reg = 'EPwm%iRegs' % {self.trig:getParameter('first_unit')}
      }
    else
      itFunction = [[
        interrupt void %(base_name)s_baseTaskInterrupt(void)
        {
          PieCtrlRegs.PIEACK.bit.ACK11 = 1;
          IER |= M_INT11;
          DISPR_dispatch();
        }
      ]] % {base_name = Target.Variables.BASE_NAME}
    end
    f.Declarations:append(itFunction)
    f.Declarations:append([[
      #pragma CODE_SECTION(%(base_name)s_hasBaseTaskOverrunOccurred, "ramfuncs")
      static inline bool %(base_name)s_hasBaseTaskOverrunOccurred() {
        return PieCtrlRegs.PIEIFR11.bit.INTx%(task_num)i;
      }
    ]] % {
      base_name = Target.Variables.BASE_NAME,
      task_num = self.task.num,
    })
    f.InterruptEnableCode:append('IER |= M_INT11;')
  end

  function Cla:finalizeThis(c)
    local cla_trig = 'CLA_TRIGGER_SOFTWARE'
    local trigSelText
    if self['trig'] ~= nil then
      if self.trig:blockMatches('timer') then
        local unit = self.trig:getParameter('unit')
        trigSelText = "CPU Timer%i" % {unit}
        cla_trig = ' CLA_TRIGGER_TINT%i' % {unit}
      elseif self.trig:blockMatches('adc') then
        local adcUnitAsChar = self.trig:getParameter('adcUnitAsChar')
        trigSelText = 'ADC%s' % {adcUnitAsChar}
        cla_trig = 'CLA_TRIGGER_ADC%s1' % {adcUnitAsChar}
      elseif self.trig:blockMatches('epwm_basic')
      or     self.trig:blockMatches('epwm_var')
      or     self.trig:blockMatches('epwm_basic_pcc')
      or     self.trig:blockMatches('epwm_var_pcc') then
        local unit = self.trig:getParameter('first_unit')
        trigSelText = 'EPWM%i' % {unit}
        cla_trig = 'CLA_TRIGGER_EPWM%iINT' % {unit}
      else
        U.error('CLA can only be triggered by a Timer, PWM or ADC block.')
      end

      -- determine if this block is supplying the actual base task trigger
      self['is_mod_trigger'] = false
      if self['modtrig'] ~= nil then
        for _, b in ipairs(self['modtrig']) do
          if b:blockMatches('tasktrigger') then
            self['is_mod_trigger'] = true
          end
        end
      end
    end
  
    local declarations = [[
         __interrupt void Cla1Task%(task_num)i();
    ]]
     
    if not self.task.is_background then
      if not self['is_mod_trigger'] then
        declarations = declarations .. [[
	    __interrupt void cla1_task%(task_num)i_isr(void)
        {
          PieCtrlRegs.PIEACK.bit.ACK11 = 1;
        }
        ]] 
      end
    end
    c.Declarations:append(declarations % {
      task_num = self.task.num
    })
    
    if not self.task.is_background then
      local init = [[
        EALLOW;
        PieVectTable.CLA1_%(task_num)i_INT  = &%(cla_isr)s;
        EDIS;

        EALLOW;
#pragma diag_suppress=770
        Cla1Regs.MVECT%(task_num)i = (uint16_t)&Cla1Task%(task_num)i;
        EDIS;
      
        CLA_setTriggerSource(CLA_TASK_%(task_num)i, %(cla_trig)s);
   
        EALLOW;
        Cla1Regs.MIER.bit.INT%(task_num)i = 1U;
        EDIS;

        PieCtrlRegs.PIEIER11.bit.INTx%(task_num)i = 1U;
      ]]
      local cla_isr = 'cla1_task%i_isr' % {self.task.num}
      if self['is_mod_trigger'] then
        cla_isr = '%s_baseTaskInterrupt' % {Target.Variables.BASE_NAME}
      end
    
      c.PreInitCode:append(init % {
        task_num = self.task.num,
        cla_trig = cla_trig,
        cla_isr = cla_isr,
        tasksrcsel_reg = 'CLA1TASKSRCSEL%i' % {math.floor(self.task.num/4)+1}
      })
    else
      local init = [[
        EALLOW;
#pragma diag_suppress=770
        Cla1Regs._MVECTBGRND = (uint16_t)&Cla1Task%(task_num)i;
        Cla1Regs._MCTLBGRND.bit.TRIGEN = 0U;
        DmaClaSrcSelRegs.CLA1TASKSRCSEL2.bit.TASK%(task_num)i = 0U; //Software
        Cla1Regs._MCTLBGRND.bit.BGEN = 1U;
        EDIS;
      ]]
      c.PreInitCode:append(init % {
        task_num = self.task.num
      })
    end
    
    if self.task.declarations ~= nil then
      for _, v in ipairs(self.task.declarations) do
        c.ClaDeclarations:append(v)
      end
    end
    
    if self.task.is_background then
      c.ClaCode:append(
        '__attribute__((interrupt("background"))) void Cla1Task%(task_num)i(void)' %
        {task_num = self.task.num})
    else
      c.ClaCode:append(
        '__attribute__((interrupt)) void Cla1Task%(task_num)i(void)' %
        {task_num = self.task.num})
    end
    
    c.ClaCode:append('{')
    for _, v in ipairs(self.task.code) do
      c.ClaCode:append(v)
    end
    c.ClaCode:append('}')
  end

  function Cla:finalize(c)
    if static[self.cpu].finalized then
      return
    end
    
    c.Include:append('cla.h')
    local declarations = [[
    ]]
    c.Declarations:append(declarations)
    
    local code = [[
      EALLOW;
      CpuSysRegs.PCLKCR0.bit.CLA1 = 1U;
      EDIS;

      EALLOW;
      Cla1Regs.MCTL.bit.IACKE = 1;
      EDIS;
    ]]
    c.PreInitCode:append(code)
    
    for _, bid in ipairs(static[self.cpu].instances) do
      local cla = globals.instances[bid]
      if cla:getCpu() == self.cpu then
        cla:finalizeThis(c)
      end
    end

    static[self.cpu].finalized = true
  end

  return Cla
end

return Module

