--[[
  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.
--]]

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 NativeLibrary = require('common.hidden.native').getBlock(globals, cpu)
  NativeLibrary.instance = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1

  function NativeLibrary:p_getDirectFeedthroughCode()
    if Block.Mask.LibName == '' then
      U.warning(
        'No %s provided to the Native Library block. This block will do nothing.' 
        % {U.paramRawLink('LibName')})
      return {}
    end

    local PreInitCode = U.CodeLines:new()
    PreInitCode:append(Block.Mask.PreInitCode)

    local IncludePath = Block.Mask.IncludeDir %
       {target_root = Target.Variables.TARGET_ROOT}
    if not Plecs:DirectoryExists(IncludePath) then
      IncludePath = '%s/%s' % {Block.Mask.ModelDir, IncludePath}
      if not Plecs:DirectoryExists(IncludePath) then
        U.error('Specified %s does not exist.' % {U.paramRawLink('IncludeDir')})
      end
    end

    local LibFilePath = Block.Mask.LibDir %
       {target_root = Target.Variables.TARGET_ROOT}
    if not Plecs:DirectoryExists(LibFilePath) then
      LibFilePath = '%s/%s' % {Block.Mask.ModelDir, LibFilePath}
      if not Plecs:DirectoryExists(LibFilePath) then
        U.error('Specified %s does not exist.' % {U.paramRawLink('LibDir')})
      end
    end

    Target.Coder.RegisterExternalLibrary(
      Block.Mask.LibName,
      {
        LibFileName = Block.Mask.LibName,
        IncludePath = IncludePath,
        LibFilePath = LibFilePath,
        PreInitCode = PreInitCode
      },
      Block.Task.Cpu)
    return {}
  end

  return NativeLibrary
end

return Module
