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

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

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

  function WriteGlobal:checkMaskParameters()
    self.varName = U.enforceMask(U.isValidCName, 'VarName')
    self.cbx_qualifier = U.enforceMask_newComboBox('VarQualifier',
                                                   {'none', 'volatile'})
  end

  function WriteGlobal: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 %(typeIn)s %(name)s;' %
      {
        typeIn = Block.InputType[1][1],
        name = self.varName,
        qualifier = self.cbx_qualifier.equals('volatile') and 'volatile' or '',
      })
    OutputCode:append('%(name)s = in[0];' % {name = self.varName})
        
    return WriteGlobal:setCode({ -- delegates to common.hidden.native
      Include = Include,
      Declarations = Declarations,
      OutputCode = OutputCode,
    })

  end

  return WriteGlobal
end

return Module
