var core = use('core')
var camera = use('camera')
var compositor = use('compositor')
var input = use('input')
var sprite_factory = use('sprite')
var text2d = use('text2d')
var random = use('random')

var GW = 1200, GH = 600

var game_cam = camera.make({width: GW, height: GH, pos: {x: GW / 2, y: GH / 2}})
var hud_cam = camera.make({width: GW, height: GH, pos: {x: GW / 2, y: GH / 2}})

input.configure({
  action_map: {
    spawn: ['mouse_button_left']
  }
})

// Bunny tracking
var bunnies = []
var bunny_sprites = []
var BUNNY_W = 26, BUNNY_H = 37

// HUD
var count_label = text2d({
  text: "Bunnies: 0", pos: {x: 10, y: GH - 25},
  plane: 'hud', size: 16, color: {r: 1, g: 1, b: 1, a: 1}
})
var fps_label = text2d({
  text: "FPS: 0", pos: {x: 10, y: GH - 45},
  plane: 'hud', size: 16, color: {r: 1, g: 1, b: 1, a: 1}
})

var fps_timer = 0
var frame_count = 0

function add_bunny(x, y) {
  var bunny = {
    vx: (random.random() * 300) - 150,
    vy: (random.random() * 300) - 150
  }
  var s = sprite_factory({
    image: "bunny",
    pos: {x: x, y: y},
    width: BUNNY_W, height: BUNNY_H,
    anchor_x: 0.5, anchor_y: 0.5,
    plane: 'game'
  })
  push(bunnies, bunny)
  push(bunny_sprites, s)
}

// Initial bunnies
var i = 0
for (i = 0; i < 100; i++) {
  add_bunny(
    random.random() * GW,
    random.random() * GH
  )
}
count_label.text = "Bunnies: " + length(bunnies)

// Mouse position tracking
var mouse_x = GW / 2, mouse_y = GH / 2

var comp_config = {
  clear: {r: 0.2, g: 0.2, b: 0.3, a: 1},
  planes: [
    {name: 'game', camera: game_cam, resolution: {width: GW, height: GH}, presentation: 'letterbox'},
    {name: 'hud', camera: hud_cam, resolution: {width: GW, height: GH}, presentation: 'stretch'}
  ]
}

core.start({
  width: 1200, height: 600, title: "Bunnymark",

  input: function(ev) {
    if (ev.type == 'mouse_motion') {
      mouse_x = ev.pos.x
      mouse_y = ev.pos.y
    }
  },

  update: function(dt) {
    // Spawn bunnies while clicking
    var down = input.player1().down()
    if (down.spawn) {
      var si = 0
      for (si = 0; si < 50; si++) {
        add_bunny(mouse_x, mouse_y)
      }
      count_label.text = "Bunnies: " + length(bunnies)
    }

    // Update all bunnies
    var b = null, s = null
    for (i = 0; i < length(bunnies); i++) {
      b = bunnies[i]
      s = bunny_sprites[i]

      s.pos.x += b.vx * dt
      s.pos.y += b.vy * dt

      if (s.pos.x < 0) { s.pos.x = 0; b.vx = -b.vx }
      else if (s.pos.x > GW) { s.pos.x = GW; b.vx = -b.vx }
      if (s.pos.y < 0) { s.pos.y = 0; b.vy = -b.vy }
      else if (s.pos.y > GH) { s.pos.y = GH; b.vy = -b.vy }
    }

    // FPS counter
    frame_count++
    fps_timer += dt
    if (fps_timer >= 1) {
      fps_label.text = "FPS: " + frame_count
      frame_count = 0
      fps_timer -= 1
    }
  },

  render: function() {
    return compositor.execute(compositor.compile(comp_config))
  }
})
