--[[
  Copyright (c) 2021 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, cpu)
  local PilOverride = require('common.block').getBlock(globals, cpu)
  if not static[cpu] then
    static[cpu] = {
      numInstances = 0,
      instances = {},
      finalized = false,
    }
  end
  PilOverride.instance = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1

  function PilOverride:p_getDirectFeedthroughCode()
    local recipe = {
      Declarations = U.CodeLines:new(),
      OutputCode = U.CodeLines:new(),
      UserData = {bid = self:getId()}
    }
    local OutputSignal = StringList:new()

    table.insert(static[self.cpu].instances, self.bid)

    -- grab (singleton) pil object
    local pilObj = self:getBlockInstance('pil')

    if not pilObj then
      pilObj = self:makeBlock('pil', self.cpu)
      pilObj:createImplicitPil(recipe)
    end

    for i = 1, #Block.InputSignal[1] do
      local name = '%s_%d' % {Block.UniqueIdentifier, i}

      if (Block.InputType[1][i] == 'bool')
      or (Block.InputType[1][i] == 'uint8_t')
      or (Block.InputType[1][i] == 'int8_t') then
        U.error('8-bit data types (%s) are not supported by PIL probes.' %
          {Block.InputType[1][i]})
      end

      pilObj:registerOverrideProbe(name, {type = Block.InputType[1][i]})

      recipe.OutputCode:append('SET_OPROBE(%(base)s_probes.%(name)s, %(input)s);' % {
        base = Target.Variables.BASE_NAME,
        name = name,
        input = Block.InputSignal[1][i],
      })
      OutputSignal:append('%s_probes.%s' % {Target.Variables.BASE_NAME, name})
    end

    recipe.OutputSignal = {OutputSignal}

    return recipe
  end

  return PilOverride
end

return Module
