{_} = require('underscore')
database = require('./database')
assets = require('../assets')

@MAX_SAVED_BATTLES = 15

class TooManyBattlesSaved extends Error
  constructor: (count) ->
    @name = "TooManyBattlesSaved"
    @message = "You have already saved #{count} replays. The maximum is #{exports.MAX_SAVED_BATTLES}."
    Error.captureStackTrace(this, TooManyBattlesSaved)

exports.TooManyBattlesSaved = TooManyBattlesSaved

@routes =
  show: (req, res) ->
    database.Battle
    .where(battle_id: req.params.id)
    .fetch()
    .then (replay) ->
      res.render('replays/show', bodyClass: 'no-sidebar', replay: replay)
    .catch (err) ->
      console.error(err.stack)
      res.render('replays/show', bodyClass: 'no-sidebar', replay: null)

  index: (req, res) ->
    console.log(req.user)
    q = new database.SavedBattles
    q= q.query()
    q = q.where(user_id: req.user.id) if req.user.name != "Deukhoofd"
    q= q.select('battle_id')
    .then (battleIds) ->
      battleIds = _.pluck(battleIds, 'battle_id')
      if battleIds.length > 0
        database.Battle
        .where('battle_id', 'in', battleIds)
        .fetchAll(columns: ['battle_id', 'players', 'name', 'format', 'created_at'])
      else
        []
    .then (replays) ->
      res.render('replays/index', bodyClass: 'no-sidebar', replays: replays)
    .catch (err) ->
      console.error(err.stack)
      res.render('replays/index', bodyClass: 'no-sidebar', replays: [])

  destroy: (req, res) ->
    battleId = req.param('id')
    database.SavedBattle.query()
    .where(user_id: req.user.id, battle_id: battleId)
    .delete()
    .then ->
      database.knex(database.SavedBattle::tableName)
      .where(battle_id: battleId).count('*')
    .then (results) ->
      # If no more saves of this replay exist, delete the replay itself.
      if Number(results[0].count) == 0
        database.Battle.query().where(battle_id: battleId).delete()
    .then ->
      res.json(ok: true)
    .catch (err) ->
      console.error(err.message)
      console.error(err.stack)
      res.json(ok: false)

@create = (user, battle) ->
  database.knex(database.SavedBattle::tableName)
  .where(user_id: user.id).count('*')
  .then (results) ->
    count = Number(results[0].count)
    if count >= exports.MAX_SAVED_BATTLES
      throw new exports.TooManyBattlesSaved(count)
  .then ->
    new database.Battle({
      battle_id: battle.id
      format: battle.format
      num_active: battle.numActive
      players: battle.playerNames.join(',')
      contents: JSON.stringify(battle.log)
      versions: assets.asHash()
    }).save().catch (err) ->
      throw err  unless /violates unique constraint/.test(err.message)
  .then ->
    new database.SavedBattle(user_id: user.id, battle_id: battle.id)
    .save().catch (err) ->
      throw err  unless /violates unique constraint/.test(err.message)
  .then ->
    battle.id
