/**
 * Javascript models for preps database objects
 * @author stevecrozz
 */

var PrepSportsGame = function(g){
    this.school_id = g.school_id;
    this.game_id = g.game_id;
    this.game_type_id = g.game_type_id;
    var m = g.game_date.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/);
    this.d = new Date();
    this.d.setFullYear(m[1]);
    this.d.setMonth(parseInt(m[2])-1);
    this.d.setDate(m[3]);
    this.d.setHours(m[4]);
    this.d.setMinutes(m[5]);
    this.d.setSeconds(m[6]);
    this.date = this.d.getTime();
    this.status = g.status;
    this.summary = g.summary;
    this.asset = g.asset;
};
$.extend(PrepSportsGame.prototype, {
    setTime: function(t) {
        var m = t.match(/(\d+):(\d+)(PM|AM)/);
        if (!m) return false;
        if (m[1] == '12') { m[1] = 0; }
        if (m[3] == 'PM')
            this.d.setHours(parseInt(m[1])+12);
        if (m[3] == 'AM')
            this.d.setHours(parseInt(m[1]));
        this.d.setMinutes(m[2]);
        this.date = this.d.getTime();
        return true;
    },
    setDate: function(d) {
        var m = d.match(/(\w{3}) (\d{1,2}), (\d{4})/);
        if (!m) return false;
        var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        for (var i in months) {
          if (months[i] == m[1]) { this.d.setMonth(i); break; }
        }
        this.d.setFullYear(m[3]);
        this.d.setDate(m[2]);
        this.date = this.d.getTime();
    },
    getUri: function(){
        return "/games/"+this.game_id;
    },
    save: function(f){
        var p = { 
            date: (this.d.getTime()/1000), 
            school_id: this.school_id, 
            status: this.status, 
            summary: this.summary, 
            game_type_id: this.game_type_id,
            asset: this.asset
        };
        $.post(this.getUri()+"/meta", p, f);
    },
    score: {
        save: function(f){
            var d = $.toJSON(this.data);
        	$.post(game.getUri()+"/scoreboard", d, f);
        },
        data: {}
    }
});
var PrepSportsMatchup = function(matchup) {
    for (var i in matchup) {
        this[matchup[i].team_id] = new PrepSportsTeam(matchup[i]);
    }
};
$.extend(PrepSportsMatchup.prototype, {
});
var PrepSportsTeam = function(team) {
	if (team.team_id) this.team_id = team.team_id;
    if (team.school_id) this.school_id = team.school_id;
    if (team.mascot) this.mascot = team.mascot;
    if (team.name) this.school_name = team.name;
    if (team.contextualInitials) {
    	this.initials = team.contextualInitials;
    } else {
    	if (team.initials) this.initials = team.initials;
    }
    if (team.league_id) this.league_id = team.league_id;
    if (team.division) this.division = team.division;
};
$.extend(PrepSportsTeam.prototype, {
    toString: function() {
        return this.school_name + ' ' + this.mascot;
    },
    save: function(p, f) {
    	$.post(p, this.toJson(), f);
    },
    toJson: function() {
    	return {
    		'team_id': this.team_id,
    		'league_id': this.league_id,
    		'division': this.division
    	}
    }
});
var PrepSportsPlay = function(actionTypeId, teamId, player1_id, player2_id, p, failed, children) {
    this.parent = parent;
    this.action_type_id = actionTypeId;
    this.game_id = null;
    this.team_id = teamId;
	if (player1_id)	this.player1_id = parseInt(player1_id);
	else this.player1_id = null;
	if (player2_id) this.player2_id = parseInt(player2_id);
	else this.player2_id = null;
	this.period = null;
	this.score_type_id = null;
	this.p = p;
	if (failed) {
		this.failed = parseInt(failed);
	} else {
		this.failed = false;
	}
	this.notes = null;
	this.children = children;
};
$.extend(PrepSportsPlay.prototype, {
	toJson: function(){
        return $.toJSON(this.toArray());
	},
	toArray: function(){
		var o = {
			action_type_id: this.action_type_id,
			team_id: this.team_id,
			player1_id: this.player1_id,
			player2_id: this.player2_id,
			period: this.period,
			score_type_id: this.score_type_id,
			float: this.p,
			failed: this.failed,
			notes: this.notes
		};
		var c = [];
		for (var i in this.children) {
			c.push(this.children[i].toArray());
		}
		if (c.length > 0) {
			o.children = c;
		}
		return o;
	},
	toString: function(){
    	return 'TODO: define toString() for PrepSportsPlay';
	},
	toHtml: function(){
		if (!this.action_type_id) { return false; }
		var parts = [];
		parts.push(matchup[this.team_id].initials);
		if (this.player1_id)
			parts.push(this.getPlayer(1).toHtml());
		if (this.p) {
			parts.push(this.p + ' yd');
		}
		var at = actionTypes[this.action_type_id];
		if (at.action_type_id == 2) {
			parts.push("field goal");
		} else {
			parts.push(actionTypes[this.action_type_id].action_name);
		}
		if (actionTypes[this.action_type_id].player2_name && this.player2_id) {
			parts.push('from ' + this.getPlayer(2).toHtml());
		}
		if (this.children) {
			for (var i in this.children) {
				cAction = this.children[i];
				if (!cAction.action_type_id) {
					return;
				}
				var cParts = [];
				if (cAction.player1_id) {
					cParts.push(cAction.getPlayer(1).toHtml());
				}
				cParts.push(actionTypes[cAction.action_type_id].action_name);
				if (cAction.failed)
					cParts.push(cAction.getFailedName());
				if (cAction.player2_id) {
					cParts.push('from ' + cAction.getPlayer(2).toHtml());
				}
				parts.push('('+cParts.join(' ')+')');
			}
		}
		return parts.join(' ');
	},
	getFailedName: function() {
		if (this.failed == 1) {
			return 'failed';
		}
		if (this.failed == 2) {
			return 'blocked';
		}
	},
	getPlayer: function(id) {
		var p = this['player'+id+'_id'];
		if (players[p]) {
			return players[p];
		} else {
			return null;
		}
	}
});
var actionTypes = {
	1: {action_type_id: 1, parent_id: 1, sport_id: 6, action_name: 'run', player1_name: 'Runner', player2_name: null, float_name: 'yards'},
	2: {action_type_id: 2, parent_id: 2, sport_id: 6, action_name: 'kick', player1_name: 'Kicker', player2_name: null, float_name: 'yards'},
	3: {action_type_id: 3, parent_id: 3, sport_id: 6, action_name: 'pass', player1_name: 'Receiver', player2_name: 'Thrower', float_name: 'yards'},
	4: {action_type_id: 4, parent_id: 4, sport_id: 6, action_name: 'safety', player1_name: 'Tackler', player2_name: null, float_name: 'yards'},
	5: {action_type_id: 5, parent_id: 1, sport_id: 6, action_name: 'kickoff return', player1_name: 'Returner', player2_name: null, float_name: 'yards'},
	6: {action_type_id: 6, parent_id: 1, sport_id: 6, action_name: 'punt return', player1_name: 'Returner', player2_name: null, float_name: 'yards'},
	7: {action_type_id: 7, parent_id: 1, sport_id: 6, action_name: 'fumble return', player1_name: 'Returner', player2_name: null, float_name: 'yards'},
	8: {action_type_id: 8, parent_id: 1, sport_id: 6, action_name: 'interception return', player1_name: 'Interceptor', player2_name: null, float_name: 'yards'}
};
var PrepSportsPlayerSet = function(players) {
	for (var i in players) {
		this[parseInt(players[i].player_id)] = new PrepSportsPlayer(players[i].player_id, players[i].firstname, players[i].lastname, players[i].team_id);
	}
};
$.extend(PrepSportsPlayerSet.prototype, {
});
var PrepSportsPlayer = function(id, fname, lname, team_id) {
	if (id) {
	    this.player_id = parseInt(id);
	} else {
	    this.player_id = 0;
	}
	this.firstname = fname;
	this.lastname = lname;
	this.nickname = null;
	this.birthdate = null;
	this.team_id = team_id;
	this.jersey_number = null;
	this.height = null;
	this.weight = null;
    this.positions = null;
};
$.extend(PrepSportsPlayer.prototype, {
    setName: function(name) {
        var nameArray = name.split(', ');
        this.firstname = nameArray[1];
        this.lastname = nameArray[0];
    },
    toString: function(lastfirst) {
        if (!this.player_id) {
            return 'team';
        }
        if (lastfirst) {
        	return this.lastname + ', ' + this.firstname;
        }
        if (this.firstname && this.firstname != '') {
            return this.firstname + ' ' + this.lastname;
        } else {
            return this.lastname;
        }
    },
    toHtml: function() {
        if (!this.player_id) {
            return 'team';
        }
        if (this.firstname) {
            return '<a href="/players/'+this.player_id+'">'+this.firstname + ' ' + this.lastname+'</a>';
        } else {
            return '<a href="/players/'+this.player_id+'">'+this.lastname+'</a>';
        }
    },
    save: function(f) {
    	if (this.id) {
    		$.post('/players/'+this.id, this.toJson(), f);
    	} else {
    		$.post('/players/new', this.toJson(), f);
    	}
    },
    getPositions: function() {
    	if (this.positions == null) {
    		return null;
    	} else {
    		return this.positions.toString();
    	}
    },
    toJson: function() {
    	return {
	    	team_id: this.team_id,
	    	firstname: this.firstname,
	    	lastname: this.lastname,
	    	jersey_number: this.jersey_number,
	    	height: this.height,
	    	weight: this.weight,
            positions: this.getPositions()
	    };
    }
});
var PrepSportsPlaySet = function(plays) {
	this.data = [];
	for (var i in plays) {
		this.addPlay(plays[i]);
	}
};
$.extend(PrepSportsPlaySet.prototype, {
	addPlay: function(play) {
		var c = [];
		for (var i in play.children) {
			c[i] = new PrepSportsPlay(play.children[i].action_type_id, play.children[i].team_id, play.children[i].player1_id, play.children[i].player2_id, play.children[i].float, play.children[i].failed);
		}
		var p = new PrepSportsPlay(play.action_type_id, play.team_id, play.player1_id, play.player2_id, play.float, play.failed, c);
		this.data.push(p);
	},
	save: function(f){
		$.post(game.getUri()+"/plays", this.toJson(), f);
	},
	toJson: function(){
		return $.toJSON(this.toArray());
	},
	toArray: function(){
		var r = [];
		for (var i in this.data) {
			r.push(this.data[i].toArray());
		}
		return r;
	},
	reorder: function(order){
		var t = [];
		for (var i in this.data) {
			t.push(i);
		}
		for (var i in order) {
			this.data[order[i]].order = i;
		}
		this.data.sort(function(a,b){
			return a.order-b.order;
		});
	}
});
var PrepSportsStat = function(typeId, teamId, player1Id, int1, int2, int3, int4) {
	this.stat_id = null;
	this.stat_type_id = parseInt(typeId);
	this.game_id = null;
	this.team_id = teamId;
	this.player1_id = player1Id;
	if (int1) this.int1 = int1;
	else this.int1 = null;
	if (int2) this.int2 = int2;
	else this.int2 = null;
	if (int3) this.int3 = int3;
	else this.int3 = null;
	if (int4) this.int4 = int4;
	else this.int4 = null;
};
$.extend(PrepSportsStat.prototype, {
	getStatName: function() {
		switch(this.stat_type_id) {
		case 1:
			return 'Rushing';
		case 2:
			return 'Passing';
		case 3:
			return 'Receiving';
		}
	},
	getTeam: function() {
		return matchup[this.team_id];
	},
	getPlayer: function() {
		return players[this.player1_id];
	},
	toArray: function(){
		return {
			stat_type_id: this.stat_type_id,
			team_id: this.team_id,
			player1_id: this.player1_id,
			int1: this.int1,
			int2: this.int2,
			int3: this.int3,
			int4: this.int4
		};
	}
});
var PrepSportsStatSet = function(stats) {
	this.data = [];
	for (var i in stats) {
		this.addStat(stats[i]);
	}
};
$.extend(PrepSportsStatSet.prototype, {
	addStat: function(s){
		this.data.push(new PrepSportsStat(s.stat_type_id, s.team_id, s.player1_id, s.int1, s.int2, s.int3, s.int4));
	},
	toArray: function(){
		var a = [];
		for (var i in this.data){
			a.push(this.data[i].toArray());
		}
		return a;
	},
	toJson: function(){
		return $.toJSON(this.toArray());
	},
	save: function(f){
		$.post(game.getUri()+'/stats', this.toJson(), f);
	}
});
var PrepSportSchool = function(s) {
	this.school_id  = s.school_id;
	this.slug       = s.slug;
	this.name       = s.name;
	this.url        = s.url;
	this.address1   = s.address1;
	this.address2   = s.address2;
	this.city       = s.city;
	this.state      = s.state;
	this.zip        = s.zip;
	this.phone      = s.phone;
	this.venue_only = s.venue_only;
};

