--[[
  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.
    Note, dsPIC does not implement this block.
    TI, ST, XMC, and SAM have identical blocks
    in their respective target libraries.
--]]
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.cbx_qualifier = U.enforceMask_newComboBox('VarQualifier',
                                                   {'none', 'volatile'})
  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.cbx_qualifier.equals('volatile') and 'volatile' or '',
      })
    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
