class   = require('vendor.30log')
inspect = require('vendor.inspect')
lume    = require('vendor.lume')

Node        = require('core.node')
ThreadNode  = require('core.thread-node')
NodeManager = require('core.node-manager')

local config = nil
if os.getenv("SIGNAGE_CONFIG") ~= nil then
  local f = loadfile(os.getenv("SIGNAGE_CONFIG"))
  if f ~= nil then
    config = f()
  else
    error("SIGNAGE_CONFIG given but could not be loaded")
  end
else
  config = require('config')
end

local push = require('vendor.push')

local lurker = require('vendor.lurker')
lurker.quiet = true
lurker.interval = 3

local debugGraph = require('vendor.debugGraph')
local fpsGraph = debugGraph:new('fps', 0, 0)
local memGraph = debugGraph:new('mem', 0, 30)

local gameWidth, gameHeight = config.renderWidth, config.renderHeight
local windowWidth, windowHeight = love.window.getDesktopDimensions()
windowWidth, windowHeight = windowWidth*.5, windowHeight*.5 --make the window a bit smaller than the screen itself

if config.environment == 'dev' then
  push:setupScreen(gameWidth, gameHeight, windowWidth, windowHeight, {fullscreen = false, resizable = true})
else
  push:setupScreen(gameWidth, gameHeight, gameWidth, gameHeight, {fullscreen = true})
end

function love.resize(w, h)
  push:resize(w, h)
  manager:resize(w, h)
end

function love.load()
  manager = NodeManager(config)
  manager:load()
  manager:resize(push:getWidth(), push:getHeight())

  love.mouse.setVisible( false )
end

function getw() return push:getWidth() end
function geth() return push:getHeight() end

function love.draw()
  push:start()

  -- Patch love.graphics.getWidth/Height to account for push
  oldw, oldh = love.graphics.getWidth, love.graphics.getHeight
  love.graphics.getWidth, love.graphics.getHeight = getw, geth

  manager:render()

  -- Draw graphs
  love.graphics.setColor(1.0, 1.0, 1.0, 0.5)

  -- love.graphics.setNewFont(10)
  -- love.graphics.print(inspect(state), 0, 60, 0)

  fpsGraph:draw()
  memGraph:draw()

  love.graphics.getWidth, love.graphics.getHeight = oldw, oldh
  push:finish()
end

function love.keypressed( key, scancode, isrepeat )
  if key == "right" then
    -- Cycle to next state
    manager.stateTime = 2137
  end
end

function love.update(dt)
  manager:update(dt)

  -- Update the graphs
  fpsGraph:update(dt)
  memGraph:update(dt)
  lurker.update()
end

function lurker.preswap(f)
  if f == 'config.lua' then
    print('config reloaded, notifying nodemanager')
    package.loaded['config'] = nil
    manager.config = require('config');
    manager:configChanged();
  elseif f:match('_thread.lua') then
    return false
  end
end
