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

local Module = {}

function Module.getBlock(globals, cpu)
  local Pil = require('common.pil_common').getBlock(globals, cpu)

  function Pil:externalModeSerialAsInt()
    return 1
  end

  function Pil:getTargetSpecificCallbackCode(c)
    -- see if the model contains epwm blocks on the same CPU
    local epwmObj = self:getBlockInstance('epwm')

    -- see if the model contains a powerstage block on the same CPU
    local powerstageObj = self:getBlockInstance('powerstage')

    local enableActuationCode = ''
    local disableActuationCode = ''
    if powerstageObj ~= nil then
      c.Include:append('plx_power.h')
      enableActuationCode = 'PLX_PWR_setPilMode(false);'
      disableActuationCode = 'PLX_PWR_setPilMode(true);'
    elseif epwmObj ~= nil then
      c.Declarations:append('extern bool EpwmForceDisable;')
      enableActuationCode = 'EpwmForceDisable = false;'
      disableActuationCode = 'EpwmForceDisable = true;'
    end

    local startTimersCode = [[
      CpuTimer0Regs.TCR.bit.TSS = 0;
      CpuTimer1Regs.TCR.bit.TSS = 0;
    ]]
    local stopTimersCode = [[
      CpuTimer0Regs.TCR.bit.TSS = 1;
      CpuTimer1Regs.TCR.bit.TSS = 1;
    ]]
    if epwmObj ~= nil then
      c.Include:append('plx_pwm.h')
      startTimersCode = startTimersCode..[[
        PLX_PWM_enableAllClocks();
      ]]
      stopTimersCode = stopTimersCode..[[
        PLX_PWM_disableAllClocks();
      ]]
    end
    local multiCpuPostFix = ''
    if Target.Variables.NUM_CPUS > 1 then
      multiCpuPostFix = '_CPU%d' % {cpu}
    end

    return {
      enableActuationCode = enableActuationCode,
      disableActuationCode = disableActuationCode,
      stopTimersCode = stopTimersCode,
      startTimersCode = startTimersCode,
      opt_cpuPostfix = multiCpuPostFix,
    }
  end

  return Pil
end

return Module
