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

  function Cpu2:createImplicit(req)

  end

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

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

    if static[self.cpu].numInstances ~= 1 then
      U.error('There should be only one (implicit) instance of the Cpu2 block.')
    end

    f.Include:append('ipc.h')

    local cpu2BootCode
    if self.cpu + 1 == 2 then
      cpu2BootCode = globals.target.getCpu2BootCodeCpu2()
    else
      cpu2BootCode = globals.target.getCpu2BootCode()
      -- memcfg needs to always be included on F28P65x when using dual CPU
      if self:targetMatches({'28P65x'}) then
        f.Include:append('memcfg.h')
      elseif not self:targetMatches({'2837x', '2838x'}) then
        U.throwUnhandledTargetError()
      end
    end

    if cpu2BootCode.declarations ~= nil then
      f.Declarations:append(cpu2BootCode.declarations)
    end
    f.PostInitCode:append(cpu2BootCode.code)

    static[self.cpu].finalized = true
  end

  return Cpu2
end

return Module

