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

--[[
    Read Global.
    Notes, XMC does not implement Qualifier
    SAM is identical to TI
    dsPic and STM do not implement this block.
--]]
local U = require('common.utils')

local static = {}

local Module = {}

function Module.getBlock(globals, cpu)
  local ReadGlobal = require('common.hidden.native').getBlock(globals, cpu)
  if not static[cpu] then
    static[cpu] = {
      numInstances = 0,
      instances = {},
      finalized = false,
    }
  end

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

  function ReadGlobal:checkMaskParameters()
    self.varName = U.enforceMask(U.isValidCName, 'VarName')
    self.varType = U.enforceMask_newComboBox('VarType',
                                             U.ENUM.DATA_TYPES).asString()
    self.qualifier = Block.Mask.VarQualifier == 2 and 'volatile' or ''
  end

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

    local Include = StringList:new();
    local Declarations = U.CodeLines:new()
    local OutputCode = U.CodeLines:new()

    Include:append('stdint.h')
    
    Declarations:append('extern %(qualifier)s %(varType)s %(name)s;'
      % {
        varType = self.varType,
        name = self.varName,
        qualifier = self.qualifier
      })
    OutputCode:append('out[0] = %(name)s;' % {name = self.varName})

    return ReadGlobal:setCode({  -- delegates to common.hidden.native
      Include = Include,
      Declarations = Declarations,
      OutputCode = OutputCode,
    })
  end

  return ReadGlobal
end

return Module
