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

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

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

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

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

    for i = 1, #Block.Mask.Value do
      local name = '%s_%d' % {Block.UniqueIdentifier, i}
  
      pilObj:registerCalibration(name, {
        type = Block.OutputType[1][i],
        val = Block.Mask.Value[i],
        min = Block.Mask.LowerLimit[i],
        max = Block.Mask.UpperLimit[i]
      })

      recipe.OutputSignal:append('%s_probes.%s' % {Target.Variables.BASE_NAME, name})
    end

    return recipe
  end

  return PilCalibrations
end

return Module
