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

local static = {}

function Module.getBlock(globals, cpu)

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

  function Interrupt:checkMaskParameters()

  end

  function Interrupt:createImplicit(params, req)
    table.insert(static[self.cpu].instances, self.bid)
    -- there can only be one Interrupt per cpu
    if static[self.cpu].numInstances ~= 1 then
      U.error("DEBUG: Multiple Interrupt blocks not supported.")
    end

    self.isrExp = params.isrCode
    self.isrEnableCode = params.isrEnableCode
    self.isrSourceBlockBid = params.bid
    
  end

  function Interrupt:p_getDirectFeedthroughCode()
    U.error("Explicit use of Interrupt via target block not supported.")
  end

  function Interrupt:finalizeThis(c)

    c.Declarations:append(self.isrExp)
    c.InterruptEnableCode:append(self.isrEnableCode)

    local isrSourceBlock = globals.instances[self.isrSourceBlockBid]
    c.PreInitCode:append(isrSourceBlock:getIsrConfigCode())
    
  end

  function Interrupt:finalize(c)
    if static[self.cpu].finalized then
      return
    end

    for _, bid in ipairs(static[self.cpu].instances) do
      local isr = globals.instances[bid]
      if isr:getCpu() == self.cpu then
        isr:finalizeThis(c)
      end
    end

    static[self.cpu].finalized = true
  end

  return Interrupt
end

return Module
