'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Game Schema
 */
var GameSchema = new Schema({
  author: {
    user: { type: Schema.ObjectId, ref: 'User'},
    score: { type: Number, default: 0 }
  },
  opponent: {
    user: { type: Schema.ObjectId, ref: 'User'},
    score: { type: Number, default: 0 }
  },
  category: { type: Schema.Types.ObjectId, ref: 'Category', index: true },
  turn: { lastUser: { type: Schema.ObjectId, ref: 'User' }, turned: { type: Date, default: null } }, // never populate
  over: { type: Boolean, default: false },
  lastQuestion: { type: Schema.Types.ObjectId, ref: 'Question', index: true },
  logs: [{ user: String, question: String, answer: String, correct: Boolean }],
  created: { type: Date },
  updated: { type: Date }
});

/**
 * Validations
 */
GameSchema.path('category').validate(
  function(category) {
    return !!category;
  },
  'Category cannot be blank'
);

// QuestionSchema.path('answers').validate(function(answers) {
//   return !!answers;
// }, 'Answers cannot be blank');

// QuestionSchema.path('correctAnswer').validate(function(correctAnswer) {
//   return !!correctAnswer;
// }, 'Correct answer cannot be blank');

GameSchema.pre('save', function(next, done){
  if (this.isNew) {
    this.created = Date.now();
  }
  this.updated = Date.now();
  next();
});

/**
 * Statics
 */
GameSchema.statics.load = function(id, cb) {
  this.findOne({_id: id})
    .populate('category')
    .populate('author.user')
    .populate('opponent.user')
    .exec(cb);
};

GameSchema.methods.whoTurn = function(cb) {
  var lastUser = this.turn.lastUser;
  var otherUser = (lastUser.equals(this.author.user._id)) ? this.opponent.user._id : this.author.user._id;

  if (!this.turn.turned) {
    return lastUser;
  }

  var maxTime = new Date(this.turn.turned.getTime());
  maxTime.setSeconds(maxTime.getSeconds() + 25);

  var turnPassed = (new Date() > maxTime);

  return (turnPassed) ? otherUser : lastUser;
};

mongoose.model('Game', GameSchema);
