--[[
  Copyright (c) 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.
--]]

--[[
    Contents of Block direct feedthough code was identical for
    ATSAM, XMC, DSPIC, and STM.

    Slightly different for TI, because it includes Block.Task.Cpu as an arg.
--]]
local U = require('common.utils')

local static = {}

local Module = {}

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

  function BuildFlags:checkMaskParameters()
  end

  function BuildFlags:p_getDirectFeedthroughCode()
    table.insert(static[self.cpu].instances, self.bid)

    local c_flags = StringList:new()
    local l_flags = StringList:new()

    for line in string.gmatch(Block.Mask.CompilerFlags, '[^\r\n]+') do
      c_flags:append(line % {target_root = Target.Variables.TARGET_ROOT})
    end

    for line in string.gmatch(Block.Mask.LinkerFlags, '[^\r\n]+') do
      l_flags:append(line % {target_root = Target.Variables.TARGET_ROOT})
    end

    Target.Coder.SetCompilerFlags(c_flags, Block.Task.Cpu)
    Target.Coder.SetLinkerFlags(l_flags, Block.Task.Cpu)
    
    return {}
  end

  return BuildFlags
end

return Module
