/**
 * http://usejsdoc.org/
 */
var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var HeroSchema = new Schema({
	hero_name: {type: String, required: true, unique: true},
	secret_name: {first: String, last: String},
	part_of_teams: Array,
	popularity: Number,
	has_weekness: Boolean,
	related_to_comic: Number,
	related_to_era: Number,
	meta: {
		age: Number,
		from: String,
		city: String
	},
	weakness: String
});

/*userSchema.methods.getDetails = function() {
	return {
		name: this.name || '',
		username: this.username || '',
		isAdmin: this.admin || '',
		roles: this.roles || '',
		age: this.meta.age || '',
		created_at: this.created_at || '',
		updated_at: this.updated_at || ''
	};
};*/

HeroSchema.pre('save', function(next, done) {
	var self = this;
	mongoose.models['Hero'].findOne({hero_name: self.hero_name}, function(err, heroRecord) {
		if(err) {
			done(err);
		} else if(heroRecord) {
			self.invalidate('hero_name', 'Hero name should be unique');
			done({message: 'Hero name should be unique'});
		} else {
			next();
		}
	});
});

HeroSchema.pre('update', function(next, done) {
	var self = this;
	mongoose.models['Hero'].findOne({hero_name: self._update.$set.hero_name}, function(err, heroRecord) {
		if(err) {
			next(err);
		} else if(heroRecord !== null && !self._conditions._id.equals(heroRecord._id)) {
			next({message: 'Update - Hero name should be unique'});
		} else {
			next();
		}
	});
});

var Hero = mongoose.model('Hero', HeroSchema);

module.exports = Hero;