app.Services.MatchService = app.Services.MatchService || {

    matchList: new app.Models.MatchCollection(),

    allMatchList: new app.Models.MatchCollection(),

    getMatches: function (callback, eventId, date) {
        if (callback) {
            app.Services.MatchService.viewCallback = callback;
        }
        var request = { "T": 91, "f": 0, "p": 0, "source": 3, "eId": eventId || 0, "hbl": 1 };
        request.d = date;
        if (date) {
            request.filterBy = "";
        } else {
            request.filterBy = "Today";
        }
        app.Services.makeRequest(request, app.Services.MatchService.parseMatches, callback);
    },

    getMatchDetail: function (callback, pollCallback, matchId, isRefresh) {
        var request = { "T": 7, "m": matchId, "t": 1, "ibe": "0", "fMC": 0, "iSe": 1 };
        if (isRefresh) {
            request.isRefresh = true;
        }
        if (pollCallback) {
            this.pollCallback = pollCallback;
        }

        app.Services.makeRequest(request, app.Services.MatchService.parseMatchDetail, callback);
    },

    getForm: function (callback, matchId) {
        var request = { "T": 104, "id": matchId };
        app.Services.makeRequest(request, app.Services.MatchService.parseForm, callback);
    },

    getMatchCastToken: function (callback, runningballId) {
        var request = { "T": 92, "rbi": runningballId };
        app.Services.makeRequest(request, function (data) {
            callback(data.vt);
        });
    },

    getMatchSurvey: function (callback, matchId) {
        var request = { "T": 35, "m": matchId, "op": 2 };
        app.Services.makeRequest(request, app.Services.MatchService.parseMatchSurvey, callback);
    },

    vote: function (callback, matchId, optionId) {
        var request = { "T": 35, "m": matchId, "op": 2, "r": [optionId], "u": Settings.getUserId() };
        app.Services.makeRequest(request, app.Services.MatchService.parseMatchSurvey, callback);
    },

    parseMatches: function (data, request) {
        if (request.filterBy == "Today") {
            app.Services.MatchService.matchList = new app.Models.MatchCollection();
            app.Services.MatchService.latestEventId = data.eId;
        } else {
            app.Services.MatchService.allMatchList = new app.Models.MatchCollection();
        }

        for (var i = 0; i < data.G.length; i++) {
            var matchGroup = data.G[i];
            var groupString = matchGroup.g;
            var groupDataArray = groupString.split(",");
            var matchArray = matchGroup.m;

            for (var j = 0; j < matchArray.length; j++) {
                var matchString = matchArray[j];
                var matchDataArray = matchString.split(",");
                var match = new app.Models.MatchModel({
                    id: matchDataArray[0],
                    homeTeam: matchDataArray[1],
                    awayTeam: matchDataArray[2],
                    homeTeamId: matchDataArray[3],
                    awayTeamId: matchDataArray[4],
                    matchState: matchDataArray[8] == "" ? 0 : matchDataArray[8],
                    homeScore: matchDataArray[9] == "" ? 0 : matchDataArray[9],
                    awayScore: matchDataArray[10] == "" ? 0 : matchDataArray[10],
                    isSummary: matchDataArray[12] != "" || matchDataArray[12] == "1",
                    matchDate: matchDataArray[13],
                    time: matchDataArray[11],
                    groupId: groupDataArray[0],
                    groupName: groupDataArray[1],
                    leagueId: groupDataArray[2],
                    leagueName: groupDataArray[3],
                    isElimination: groupDataArray[4] == "1",
                    seasonId: groupDataArray[5],
                    cupId: groupDataArray[6]
                });
                match.set({ isLive: match.getIsLive(), isLiveOrNotStarted: match.getIsLiveOrNotStarted(), isFinished: match.getIsFinished() });
                if (request.filterBy == "Today") {
                    app.Services.MatchService.matchList.add(match);
                } else {
                    app.Services.MatchService.allMatchList.add(match);
                }

                match.set("isSelected", Settings.isSubscribed({ assetId: match.get("id"), assetType: 1 }));

            }
        }
        if (request.filterBy == "Today") {
            app.Services.MatchService.viewCallback(app.Services.MatchService.matchList);
        } else {
            app.Services.MatchService.viewCallback(app.Services.MatchService.allMatchList);
        }
        if (!app.Services.MatchService.poll.latestEventId) {
            app.Services.MatchService.poll.init(function (events) {
                app.Services.MatchService.parseEventData(events);
            }, function () {
                console.log("error");
            }, app.Services.MatchService.latestEventId);
        }
    },

    parseEventData: function (data) {
        var eventList = data;

        for (var iEvent = 0; iEvent < eventList.length; iEvent++) {
            var event = eventList[iEvent];

            var eventId = event[0];
            var eventType = event[1];
            // check if event already done.
            if (eventId <= app.Services.MatchService.latestEventId) {
                continue;
            }
            // refresh Scores;
            if (eventType == 1) {
                app.Services.MatchService.getMatches(null, eventId);
                break;
            }

            //updateMinutes;
            if (eventType == 2) {
                app.Services.MatchService.matchList.updateMinutes();
                continue;
            }

            var matchId = event[2];
            var matchState = event[9];
            var time = event[4];
            if (!isNaN(parseFloat(time)) && isFinite(time)) {
                time = (time + "'");
            } else {
                /*
                NotStarted = 0,
        FHTPlaying = 1,
        HTScore = 2,
        SHTPlaying = 3,
        FTScore = 4,
        ETPlaying = 5,
        ETScore = 6,
        ETPenalty = 7,
        ETPenaltyScore = 8,
        Postponed = 9,
        ByDecision = 10,
        Suspended = 11
                */
                if (matchState == 2) {
                    time = "HT";
                }else if (matchState == 4) {
                    time = "FT";
                }else if (matchState == 5 || matchState == 6) {
                    time = "ET";
                }else if (matchState == 9) {
                    time = "PP";
                }else if (matchState == 10) {
                    time = "DEC";
                }else if (matchState == 11) {
                    time = "SUSP";
                }
            }
        
            var homeScore = event[5];
            var awayScore = event[6];
            
            var eventType1 = event[10];
            var eventType2 = event[11];

            var match = app.Services.MatchService.matchList.get(matchId);
            if (match) {
                match.set({ homeScore: homeScore, awayScore: awayScore, matchState: matchState, time: time });
                match.set({ isLive: match.getIsLive(), isLiveOrNotStarted: match.getIsLiveOrNotStarted(), isFinished: match.getIsFinished() });
            }

        }
    },

    parseMatchDetail: function (data, request, callback, pollCallback) {
        var matchDetailData = data.D;
        var match = new app.Models.MatchModel({
            id: matchDetailData.mI,
            runningballId: matchDetailData.mRBI,
            homeTeam: matchDetailData.hN,
            awayTeam: matchDetailData.aN,
            homeTeamId: matchDetailData.hNId,
            awayTeamId: matchDetailData.aNId,
            homeLogo: "http://im.cdn.md/img/logo/75/" + matchDetailData.hNId + ".png",
            awayLogo: "http://im.cdn.md/img/logo/75/" + matchDetailData.aNId + ".png",
            matchState: matchDetailData.mS,
            matchDate: matchDetailData.mD,
            leagueName: matchDetailData.cN,
            referee: matchDetailData.r1,
            homeManager: matchDetailData.hR,
            awayManager: matchDetailData.aR,
            stadium: matchDetailData.sN,
            time: matchDetailData.pS,
            score: matchDetailData.s,
            halfTimeScore: matchDetailData.hF,
            isElimination: matchDetailData.mEl == "1",
            firstLegHomeScore: matchDetailData.fHS,
            firstLegAwayScore: matchDetailData.fAS,
            isInBlacklist: matchDetailData.ibl == "1"
        });

        match.set({ isLive: match.getIsLive(), isLiveOrNotStarted: match.getIsLiveOrNotStarted(), isFinished: match.getIsFinished() });
        match.set("isSelected", Settings.isSubscribed({ assetId: match.get("id"), assetType: 1 }));
        var events = new app.Models.EventCollection();
        var prevEventType = 0;
        for (var i = 0; i < matchDetailData.E.length; i++) {
            var eventData = matchDetailData.E[i];
            var eventSide = eventData.hI > 0 ? 1 : 2;
            var eventType = eventSide == 1 ? eventData.hI : eventData.aI;
            var homePlayerName = app.Services.MatchService.getShortName(eventData.hN);
            var awayPlayerName = app.Services.MatchService.getShortName(eventData.aN);
            if (eventType != 6) {
                var event = new app.Models.EventModel({
                    eventSide: eventSide,
                    homeEventPlayer: homePlayerName,
                    awayEventPlayer: awayPlayerName,
                    homeEventMinute: eventSide == 1 ? eventData.t : "",
                    awayEventMinute: eventSide == 2 ? eventData.t : "",
                    eventType: eventSide == 1 ? eventData.hI : eventData.aI,
                });
                events.add(event);

            } else {
                if (prevEventType == 5) {
                    var prevEvent = events.last();
                    prevEvent.set("homeEventRelatedPlayer", homePlayerName);
                    prevEvent.set("awayEventRelatedPlayer", awayPlayerName);
                }
            }
            prevEventType = eventType;
        }

        match.set("events", events);

        var homeSquad = new app.Models.PlayerCollection();
        var homeSubstitutes = new app.Models.PlayerCollection();
        var awaySquad = new app.Models.PlayerCollection();
        var awaySubstitutes = new app.Models.PlayerCollection();

        for (var i = 0; i < matchDetailData.H.length; i++) {
            var playerData = matchDetailData.H[i];
            var player = new app.Models.PlayerModel({
                name: playerData.pN,
                id: playerData.pId,
                shirtNumber: playerData.uN,
                event1: playerData.e1,
                event2: playerData.e2,
                goalCount: playerData.e3,
                substitutionTime: playerData.t
            });
            homeSquad.add(player);
        }

        for (var i = 0; i < matchDetailData.HS.length; i++) {
            var playerData = matchDetailData.HS[i];
            var player = new app.Models.PlayerModel({
                name: playerData.pN,
                id: playerData.pId,
                shirtNumber: playerData.uN,
                event1: playerData.e1,
                event2: playerData.e2,
                goalCount: playerData.e3,
                substitutionTime: playerData.t
            });
            homeSubstitutes.add(player);
        }

        for (var i = 0; i < matchDetailData.A.length; i++) {
            var playerData = matchDetailData.A[i];
            var player = new app.Models.PlayerModel({
                name: playerData.pN,
                id: playerData.pId,
                shirtNumber: playerData.uN,
                event1: playerData.e1,
                event2: playerData.e2,
                goalCount: playerData.e3,
                substitutionTime: playerData.t
            });
            awaySquad.add(player);
        }

        for (var i = 0; i < matchDetailData.AS.length; i++) {
            var playerData = matchDetailData.AS[i];
            var player = new app.Models.PlayerModel({
                name: playerData.pN,
                id: playerData.pId,
                shirtNumber: playerData.uN,
                event1: playerData.e1,
                event2: playerData.e2,
                goalCount: playerData.e3,
                substitutionTime: playerData.t
            });
            awaySubstitutes.add(player);
        }

        match.set("homeSquad", homeSquad);
        match.set("awaySquad", awaySquad);
        match.set("homeSubstitutes", homeSubstitutes);
        match.set("awaySubstitutes", awaySubstitutes);

        var stats = new Backbone.Collection([], {
            model: app.Models.MatchStatModel
        });
        for (var i = 0; i < matchDetailData.MS.length; i++) {
            var matchStatData = matchDetailData.MS[i];
            var matchStat = new app.Models.MatchStatModel({
                statisticType: matchStatData.st,
                home: matchStatData.h,
                away: matchStatData.a

            });
            var totalStat = matchStat.get("home") + matchStat.get("away");
            var homeWidth = ((matchStat.get("home") / totalStat) * 100) + "%";
            var awayWidth = ((matchStat.get("away") / totalStat) * 100) + "%";
            matchStat.set("homeWidth", homeWidth);
            matchStat.set("awayWidth", awayWidth);
            matchStat.set("header", matchStat.getHeader());
            stats.add(matchStat);
        }
        match.set("stats", stats);
        if (match.get("isElimination")) {
            var homeScore, awayScore;
            var score = match.get("score");
            if (score != "-") {
                homeScore = parseInt(score.split("-")[0].trim());
                awayScore = parseInt(score.split("-")[1].trim());
            } else {
                homeScore = awayScore = 0;
            }
            if (match.get("firstLegHomeScore")) {
                var aggregateScore = (homeScore + match.get("firstLegHomeScore")) + " - " + (awayScore + match.get("firstLegAwayScore"));
                match.set("aggregateScore", aggregateScore);
            }
        }
        match.set("descriptionString", (match.get("halfTimeScore") != "" ? "HT " + match.get("halfTimeScore") : "") + (match.has("aggregateScore") ? " (Agg " + match.get("aggregateScore") + ")" : ""));

        if (!app.Services.MatchService.poll.sequence && match.getIsLiveOrNotStarted()) {
            app.Services.MatchService.poll.init(function (score, time, isUpdate) {
                var matchUpdate = new app.Models.MatchModel({
                    time: time,
                    score: score,
                    isUpdateNecessary: isUpdate
                });

                app.Services.MatchService.pollCallback(matchUpdate);
            }, function () {
                console.log("error");
            }, 0, match.get("id"), 0);
        }

        callback(match);
    },

    getShortName: function (name) {
        if (name == "") return name;

        if (name.indexOf("(") > -1) {
            name = name.substring(0, name.indexOf("("));
        }
        name = name.trim().replace(" - ", "-");
        var nameArr = name.split(' ');
        if (nameArr.length == 2) {
            return nameArr[0].substring(0, 1) + "." + nameArr[1];
        }
        var shortName = "";
        for (var i = 0; i < nameArr.length - 1; i++) {
            var namePart = nameArr[i];
            shortName += namePart.substring(0, 1) + ".";
        }
        shortName += nameArr[nameArr.length - 1];

        return shortName;

    },

    parseForm: function (data, request, callback) {
        var homeMatches = new app.Models.MatchCollection;
        var awayMatches = new app.Models.MatchCollection;
        var oldMatches = new app.Models.MatchCollection;
        for (var i = 0; i < data.HM.length; i++) {
            var matchData = data.HM[i];
            var match = new app.Models.MatchModel({
                id: matchData.mId,
                homeTeam: matchData.hN,
                awayTeam: matchData.aN,
                homeScore: matchData.hS,
                awayScore: matchData.aS,
                matchState: matchData.mS,
                matchDate: DateUtils.getShortDate(matchData.mD),
                matchResult: matchData.mR
            });
            homeMatches.add(match);
        }

        for (var i = 0; i < data.AM.length; i++) {
            var matchData = data.AM[i];
            var match = new app.Models.MatchModel({
                id: matchData.mId,
                homeTeam: matchData.hN,
                awayTeam: matchData.aN,
                homeScore: matchData.hS,
                awayScore: matchData.aS,
                matchState: matchData.mS,
                matchDate: DateUtils.getShortDate(matchData.mD),
                matchResult: matchData.mR
            });
            awayMatches.add(match);
        }

        for (var i = 0; i < data.OM.length; i++) {
            var matchData = data.OM[i];
            var match = new app.Models.MatchModel({
                id: matchData.mId,
                homeTeam: matchData.hN,
                awayTeam: matchData.aN,
                homeScore: matchData.hS,
                awayScore: matchData.aS,
                matchState: matchData.mS,
                matchDate: DateUtils.getShortDate(matchData.mD)

            });
            oldMatches.add(match);
        }

        callback({ homeMatches: homeMatches, awayMatches: awayMatches, oldMatches: oldMatches });
    },

    parseMatchSurvey: function (data, request, callback) {
        var votedOptionId = Settings.getVotedOption(request.m);
        var survey = new app.Models.SurveyModel({
            isVotable: votedOptionId || (request.r && request.r.length) ? false : data.s == 0
        });

        var options = [];
        for (var i = 0; i < data.O.length; i++) {
            var optionData = data.O[i];
            var resultData = data.R[i];
            var option = {
                id: optionData.i,
                text: i != 1 ? optionData.t : "Draw",
                percentage: resultData.p
            };
            option.isSelected = option.id == votedOptionId || (request.r && request.r.length ? request.r[0] == option.id : false);
            options.push(option);
        }

        survey.set("options", options);

        callback(survey);
    },

    poll: {

        init: function (succ, err, eventId, matchId) {
            if (matchId) {
                this.matchId = matchId;
                this.sequence = 0;
            } else {
                this.latestEventId = eventId;
            }
            this.events = [];
            this._url = "http://p22.cdn.md/football/?eId=";
            this._matchUrl = "http://p22.cdn.md/m/?id={{matchId}}&s={{seq}}";
            this.successFn = succ;
            this.errorFn = err;
            this.subscribe();
        },

        _getUrl: function () {
            if (this.matchId) {
                return this._matchUrl.replace("{{matchId}}", this.matchId).replace("{{seq}}", this.sequence);
            } else {
                return this._url + this.latestEventId;
            }
        },
        subscribe: function () {
            var self = this;
            var xhr = new XMLHttpRequest({ mozSystem: true });
            xhr.timeout = 1000 * 60 * 3;
            xhr.onload = function (e) {
                if (xhr.status === 200 || xhr.status === 0) {
                    var cleanResponse = xhr.responseText.replace("_p(", "").slice(0, -2);
                    var data = JSON.parse(cleanResponse);
                    if (data.s == -1) {
                        setTimeout(function () { self.subscribe(); }, 1000 * 60);
                    } else {
                        if (self.matchId) {
                            var sequenceObj = data.s;
                            var isUpdate = false;

                            if (sequenceObj.seq > self.sequence) {
                                if (self.sequence) {
                                    isUpdate = true;
                                }
                                self.sequence = sequenceObj.seq;
                            }
                            self.successFn(sequenceObj.s, sequenceObj.st, isUpdate);

                        } else {
                            var events = data.e;
                            if (events.length > 0) {
                                self.latestEventId = events[events.length - 1][0];
                                self.events = events;
                                self.successFn(events);
                            }
                        }
                        setTimeout(function () { self.subscribe(); }, 1000);
                    }
                } else {
                    self.errorFn();
                    setTimeout(function () { self.subscribe(); }, 5000);

                }
            };
            xhr.open("GET", self._getUrl(), true);
            xhr.send();
        }
    }

};
