--[[
  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 Module = {}
local U = require('common.utils')

local static = {}

function Module.getBlock(globals, cpu)

  local Clock = require('common.block').getBlock(globals, cpu)
  if static[cpu] == nil then
    static[cpu] = {
      numInstances = 0,
      finalized = false,
    }
  end
  Clock["instance"] = static[cpu].numInstances
  static[cpu].numInstances = static[cpu].numInstances + 1

  function Clock:getPublicParameters()
    assert(static.clockConfigParameters ~= nil)
    return U.contractLockTable({
      opt_pllRawClkHz = static.clockConfigParameters.pllConfig.pllRawClkHz,
    })
  end

  function Clock:createImplicit()
    if static.clockConfigParameters == nil then
      static.clockConfigParameters = globals.target.getClockConfiguration()
    end
  end

  function Clock:p_getDirectFeedthroughCode()
    U.error("Explicit use of CLOCK via target block not supported.")
  end

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

    local clockConfig
    if self.cpu + 1 == 2 then
      clockConfig = globals.target.getClockConfigurationCodeCpu2(static.clockConfigParameters)
    else
      clockConfig = globals.target.getClockConfigurationCode(static.clockConfigParameters)
    end

    f.Declarations:append(clockConfig.declarations)
    f.PreInitCode:append(clockConfig.code)

    globals.syscfg:setEntry('System', {
    	clk = globals.target.getCleanSysClkHz(),
      core = self.cpu + 1
  	})

    static[self.cpu].finalized = true
  end

  return Clock
end

return Module

