﻿function MatchHelper() {
    this.list = [];
    this.init();
}

MatchHelper.getPoints = function (code, match) {
    if (match.hCode === code) {
        if (match.hScore > match.aScore) {
            return 3;
        }
        return match.hScore < match.aScore ? 0 : 1
    }
    else if (match.aCode === code) {
        if (match.hScore > match.aScore) {
            return 0;
        }
        return match.hScore < match.aScore ? 3 : 1
    }
    return 0;
};

MatchHelper.prototype = {
    list: null,
    ready: false,

    url: '/Match/AllMatches',
    details: null,

    init: function () {
        var self = this;

        // perform ajax to get the match details
        ajaxHelper.call(
            {
                context: self,
                url: self.url,
                type: 'GET',
                cache: true,
                success: function (details) {
                    self.details = details;
                    self.process();
                    self.ready = true;

                    self.execute();
                },
                error: function () {
                    alert("Mac detaylari getirilemedi. Daha sonra tekrar deneyiniz.");
                }
            });

    },

    sortByMatchType: function () {
        this.details.sort(function (m1, m2) {

            if (!m1.date) {
                m1.date = Date.parseInvariant(m1.time, "yyyy-MM-dd HH:mm");
            }

            if (!m2.date) {
                m2.date = Date.parseInvariant(m2.time, "yyyy-MM-dd HH:mm");
            }

            if (!m1.type) {
                m1.type = parseInt(m1.mType, 10);
            }

            if (!m2.type) {
                m2.type = parseInt(m2.mType, 10);
            }

            if (m1.mType != m2.mType) {
                return m1.mType < m2.mType ? -1 : 1;
            }

            if (m1.time != m2.time) {
                return m1.time < m2.time ? -1 : 1;
            }

            return m1.id - m2.id;
        });
    },

    getMatches: function () {
        var i, len, m,
            macthes,
            details = this.details;

        if (!this.matches) {
            matches = [];
            for (i = 0, len = details.length; i < len; i++) {
                m = details[i];

                if (m.date.getFullYear() !== 2020) {
                    matches.push(m);
                }
            }

            matches.sort(function (m1, m2) {
                if (m1.hScore >= 0) {
                    if (m2.hScore >= 0) {
                        return m2.date - m1.date;
                    }
                    else {
                        return 1;
                    }
                }
                else {
                    if (m2.hScore >= 0) {
                        return -1;
                    }
                    else {
                        return m1.date - m2.date;
                    }
                }
            });

            this.matches = matches;
        }
        return this.matches;
    },

    getStandings: function (prefix) {
        var i, l, m,
            ht, at, teamsHash, teams;

        prefix = prefix || "o";

        if (!this.teams) {
            teamsHash = {};
            teams = [];

            for (i = 0, l = this.details.length; i < l; i++) {
                m = this.details[i];

                ht = teamsHash[m.hCode];
                if (!ht) {
                    ht = { code: m.hCode, name: m.hName, oMatches: [], hMatches: [], aMatches: [] };
                    teamsHash[m.hCode] = ht;
                    teams.push(ht);
                }

                at = teamsHash[m.aCode];
                if (!at) {
                    at = { code: m.aCode, name: m.aName, oMatches: [], hMatches: [], aMatches: [] };
                    teamsHash[m.aCode] = at;
                    teams.push(at);
                }

                if (m.hScore >= 0 && m.aScore >= 0) {

                    ht.oPlayed = (ht.oPlayed || 0) + 1;
                    ht.hPlayed = (ht.hPlayed || 0) + 1;
                    ht.oGoals = (ht.oGoals || 0) + m.hScore;
                    ht.hGoals = (ht.hGoals || 0) + m.hScore;
                    ht.oConceded = (ht.oConceded || 0) + m.aScore;
                    ht.hConceded = (ht.hConceded || 0) + m.aScore;
                    ht.hMatches.push(m);
                    ht.oMatches.push(m);

                    at.oPlayed = (at.oPlayed || 0) + 1;
                    at.aPlayed = (at.aPlayed || 0) + 1;
                    at.oGoals = (at.oGoals || 0) + m.aScore;
                    at.aGoals = (at.aGoals || 0) + m.aScore;
                    at.oConceded = (at.oConceded || 0) + m.hScore;
                    at.aConceded = (at.aConceded || 0) + m.hScore;
                    at.oMatches.push(m);
                    at.aMatches.push(m);

                    if (m.hScore > m.aScore) {
                        ht.oWin = (ht.oWin || 0) + 1;
                        ht.hWin = (ht.hWin || 0) + 1;
                        ht.oPoints = (ht.oPoints || 0) + 3;
                        ht.hPoints = (ht.hPoints || 0) + 3;

                        at.oLoss = (at.oLoss || 0) + 1;
                        at.aLoss = (at.aLoss || 0) + 1;
                        at.oPoints = (at.oPoints || 0) + 0;
                    }
                    else if (m.hScore < m.aScore) {
                        at.oWin = (at.oWin || 0) + 1;
                        at.aWin = (at.aWin || 0) + 1;
                        at.oPoints = (at.oPoints || 0) + 3;
                        at.aPoints = (at.aPoints || 0) + 3;

                        ht.oLoss = (ht.oLoss || 0) + 1;
                        ht.hLoss = (ht.hLoss || 0) + 1;
						ht.oPoints = (ht.oPoints || 0) + 0;
                    }
                    else {
                        ht.oDraw = (ht.oDraw || 0) + 1;
                        ht.hDraw = (ht.hDraw || 0) + 1;
                        ht.oPoints = (ht.oPoints || 0) + 1;
                        ht.hPoints = (ht.hPoints || 0) + 1;

                        at.oDraw = (at.oDraw || 0) + 1;
                        at.aDraw = (at.aDraw || 0) + 1;
                        at.oPoints = (at.oPoints || 0) + 1;
                        at.aPoints = (at.aPoints || 0) + 1;
                    }
                }
            }
            this.teams = teams;
        }

        this.teams.sort(function (t1, t2) {
            if (t1[prefix + "Points"] === t2[prefix + "Points"]) {
                var team1Avg = t1[prefix + "Goals"] - t1[prefix + "Conceded"];
                var team2Avg = t2[prefix + "Goals"] - t2[prefix + "Conceded"];
                if (team1Avg != team2Avg) {
                    return team2Avg - team1Avg;
                }
                else {
                    if (t1[prefix + "Goals"] !== t2[prefix + "Goals"]) {
                        return t2[prefix + "Goals"] - t1[prefix + "Goals"];
                    }
                    else {
                        return t2[prefix + "Played"] - t1[prefix + "Played"];
                    }
                }
            }
            return t2[prefix + "Points"] - t1[prefix + "Points"];
        });

        return this.teams;
    },

    openMatchDetails: function (match) {
        var options = { modal: true, width: 400, height: 300 };
        ajaxHelper.call(
            {
                context: this,
                url: '/Admin/MatchDetails',
                type: 'GET',
                cache: true,
                success: function (result) {
                    var $content = $(result.message).attr("title", "Maç Detayları");
                    $content.data("match-id", match.id);
                    $content.data("match-time", match.matchTime);
                    var $matchScores = $content.find("table.match-scores");

                    $.each(["home", "away"], function (ind, team) {
                        var i, len, score, $row = $matchScores.find("tr." + team);

                        // Setting team name
                        $row.find(".team-name").text(match[team + "Name"]);
                        // Setting width for score inputs
                        var $inputs = $row.find("input[type='text']").width("3em").attr("maxlength", "2");

                        score = match[team + "ScoreStr"] || "";
                        for (var i = 0, len = score.length / 2; i < len; i++) {
                            $inputs.eq(i).val(parseInt(score.substr(i * 2, 2), 10));
                            if (i === (len - 1) && i > 0) {
                                $inputs.eq(i).css("font-weight", "bold");
                            }
                        }
                    });

                    $content.find(".match-time").val(match.matchTime);

                    var $matchPredictions = $content.find(".match-predictions");

                    ajaxHelper.call(
                    {
                        context: this,
                        url: '/Admin/MatchPredictions',
                        type: 'GET',
                        data: { matchId: match.id },
                        cache: false,
                        success: function (result) {
                            $.each(result, function (ind, prediction) {
                                $("<li />")
                                    .text(String.format("{0}. {1} ({2})", ind + 1, prediction.u, prediction.p))
                                    .css("font-weight", prediction.j ? "bold" : "normal")
                                    .appendTo($matchPredictions);
                            });
                        }
                    });


                    options.buttons = { "Kaydet": function (ui) {
                        var $host = $(this),
                            matchDetails = { id: $host.data("match-id"), time: $host.data("match-time"), home: [], away: [] };

                        $.each(["home", "away"], function (ind, team) {
                            var i, score, $row = $matchScores.find("tr." + team);

                            // Setting width for score inputs
                            var $inputs = $row.find("input[type='text']");
                            for (var i = 0; i < 4; i++) {
                                score = $.trim($inputs.eq(i).val());
                                if (score.length) {
                                    matchDetails[team].push(score);
                                }
                                else {
                                    break;
                                }
                            }

                            matchDetails[team] = matchDetails[team].join(":");
                        });

                        var matchTime = $.trim($host.find(".match-time").val());
                        if (matchTime.length) {
                            matchDetails.time = matchTime;
                        }

                        ajaxHelper.call(
                        {
                            context: this,
                            url: '/Admin/MatchDetails',
                            data: matchDetails,
                            type: 'POST',
                            success: function (result) {
                                $host.dialog("close");
                            },
                            error: function (error) {
                                $host.find(".error").text(error.message);
                            }
                        });
                    }
                    };

                    options.close = function () {
                        $(this).remove();
                    };

                    $content.appendTo(document.body).dialog(options);
                },
                error: function (error) {
                    $("<div />").appendTo(document.body).html(error.message).dialog(options);
                }
            });
    },

    process: function () {
        this.sortByMatchType();
    },
    execute: function () {
        var self = this;
        $.each(this.list, function () {
            this.call(self);
        });
    },
    using: function (f) {
        if (!this.ready) {
            // Match details didn't load yet, adding to the inner list
            // to be executed later
            if ($.isFunction(f)) {
                this.list.push(f);
            }
        }
        else {
            // run immediately
            f.call(this);
        }
    }
}

var matchHelper = new MatchHelper();

TY.loaded("matchHelper", matchHelper);

