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

  StackMon.instance = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1

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

    globals.syscfg:addPeripheralEntry('stackMon', {cpu = self.cpu})

    return {
      OutputSignal = {
        [1] = {'PLXHAL_StackMon_getStackUseagePercent()'},
      },
      UserData = {bid = self:getId()},
    }
  end

  function StackMon:finalize(c)
    if static[self.cpu].finalized then
      return
    end

    if static[self.cpu].numInstances ~= 1 then
      U.error([[
        There may only be once instance of the Stack Monitor block per CPU.
      ]])
    end

    c.Include:append('plx_stack_monitor.h')
    c.Include:append('plx_hal.h')

    c.Declarations:append([[
      PLX_StackMon_Handle_t StackMonHandle;
      PLX_StackMon_Obj_t StackMonObj;

      void PLXHAL_StackMon_paintStack() {
        StackMonHandle = PLX_StackMon_init(&StackMonObj, sizeof(StackMonObj));
        PLX_StackMon_paintStack(StackMonHandle);
      }

      float PLXHAL_StackMon_getStackUseagePercent() {
        return PLX_StackMon_getStackUseagePercent(StackMonHandle);
      }
    ]])

    c.BackgroundTaskCodeBlocks:append([[
      PLX_StackMon_updateStackUseage(StackMonHandle);
    ]])

    static[self.cpu].finalized = true
  end

  return StackMon
end

return Module
