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

  function Pga:createImplicit(pga, params, req)
    static[self.cpu].instances[pga] = self.bid
    self.pga = pga
    self.gain = params.gain
    self.rf = params.rf
    self:logLine('PGA%d implicitly created.' % {self.pga})
  end

  function Pga:p_getDirectFeedthroughCode()
    U.error('Target IO Block not supported.')
  end

  function Pga:finalizeThis(c)
    c.PreInitCode:append(
      'PLX_PGA_enable(%d, (uint16_t)%d, (uint16_t)%d);' 
      % {self.pga, self.gain, self.rf})
  end

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

    c.Include:append('plx_pga.h')

    c.PreInitCode:append([[
      PLX_PGA_sinit();
    ]])

    for _, bid in U.pairsSorted(static[self.cpu].instances) do
      local pga = globals.instances[bid]
      if pga:getCpu() == self.cpu then
        pga:finalizeThis(c)
      end
    end

    static[self.cpu].finalized = true
  end

  return Pga
end

return Module
