--[[
  Copyright (c) 2022, 2024 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, optionalCpu)
  local cpu = optionalCpu or 0
  if not static[cpu] then
    static[cpu] = {
      numInstances = 0,
      instances = {},
      finalized = false,
    }
  end

  local NativeCode = require('common.hidden.native').getBlock(globals, cpu)
  NativeCode.instance = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1



  function NativeCode:p_getDirectFeedthroughCode()
    local bid = self:getId()

    local Include = StringList:new()
    local Declarations = U.CodeLines:new()
    local InitCode = U.CodeLines:new()
    local PostInitCode = U.CodeLines:new()
    local OutputCode = U.CodeLines:new()
    local BackgroundCode = U.CodeLines:new()

    --[[ Substitute block id new and old way:
        gsub with |<BID>| and %(bid)d.
    --]]
    function subBid(s)
      local bid = self:getId()
      return string.gsub(s, '|<BID>|', tostring(bid)) % {bid = bid}
    end

    Declarations:append(subBid(Block.Mask.Declarations))
    InitCode:append(subBid(Block.Mask.InitCode))
    PostInitCode:append(subBid(Block.Mask.PostInitCode))
    OutputCode:append(subBid(Block.Mask.StepCode))
    BackgroundCode:append(subBid(Block.Mask.BackgroundCode))

    return NativeCode:setCode({
      Include = Include,
      Declarations = Declarations,
      InitCode = InitCode,
      PostInitCode = PostInitCode,
      OutputCode = OutputCode,
      BackgroundCode = BackgroundCode
    })
  end

  return NativeCode
end

return Module
