# Central game object that handles our loop
module.exports = class Game

  constructor: ->
    @states = []

  # Create the primary screen canvas and start the animation loop
  start: (opts = {}) ->
    @environment =
      element  : opts.element ? document.body
      width    : opts.width ? global.innerWidth
      height   : opts.height ? global.innerHeight
      isCocoon : navigator.isCocoonJS?

    @bgColor = opts.bgColor ? null

    @_createScreen()
    @_startLoop()
    @log 'game started'
    global.game = this

  # Push a new state T onto the stack
  startState: (T) ->

  # Should be batched and outputted occassionally to avoid slowdown
  log: -> Game.log arguments...
  @log: (m) -> console?.log? m

  # Primary render loop
  _render: (time) =>
    requestAnimationFrame @_render
    delta = if @lastRender? then time - @lastRender else 0
    @lastRender = time

    # Easy bg, optional
    if @bgColor?
      @ctx.globalCompositeOperation = Layer.SOURCE_OVER
      @ctx.fillStyle = @bgColor
      @ctx.fillRect 0, 0, @screen.width, @screen.height

    # Delegate rendering to the current state

    @frameNumber++
    return

  # Create the actual DOM element for our screen canvas, with some special
  # cases if we're running on CocoonJS
  _createScreen: (height, width) ->
    el = if @environment.isCocoon then 'screencanvas' else 'canvas'
    @screen = document.createElement el
    @screen.width = @environment.width
    @screen.height = @environment.height
    @screen.setAttribute 'screencanvas', 'true' if @environment.isCocoon
    @ctx = @screen.getContext '2d'
    @environment.element.appendChild @screen
    return

  # Fire the raf
  _startLoop: ->
    @frameNumber = 0
    requestAnimationFrame @_render

  # --------------------------------------------------------------------------
  # polyfill raf

  global.requestAnimationFrame = requestAnimationFrame ?
    webkitRequestAnimationFrame ?
    mozRequestAnimationFrame


