var app = app || {};

app.FavoritesView = Backbone.View.extend({
    el: "#matches",
    matchList: new app.Models.MatchCollection(),
    initialize: function () {
        var self = this;

        $("#menu").mmenu({ position: "right" }, {});
        app.Services.NotificationService.getSubscribedNotifications(function (matches, teams, leagues) {
            self.render(matches, teams, leagues);
            app.Services.MatchService.poll.init(self.applyEvents, function () {
                console.log("error");
            }, 0);
        }, false);
    },
    render: function (matches, teams, leagues) {
        this.matchList = matches;
        var myScoreHolder = $("#matches");
        var myTeamHolder = $("#teams");
        var myLeagueHolder = $("#leagues");

        if (matches.length > 0) {
            for (var i = 0; i < this.matchList.length; i++) {
                var item = this.matchList.at(i);
                var match = new app.MatchView({ model: item });
                myScoreHolder.find("tbody").append(match.render().el);
                myScoreHolder.show();
                $("#no-matches").hide();
            }
        }

        if (teams.length > 0) {
            for (var i = 0; i < teams.length; i++) {
                var item = teams.at(i);
                var team = new app.TeamView({ model: item });
                myTeamHolder.append(team.render().el);
                myTeamHolder.show();
                $("#no-teams").hide();
            }
        }

        if (leagues.length > 0) {
            for (var i = 0; i < leagues.length; i++) {
                var item = leagues.at(i);
                var league = new app.LeagueHeaderView({ model: item });
                myLeagueHolder.append(league.render().el);
                myLeagueHolder.show();
                $("#no-leagues").hide();

            }
        }
        return this;
    },

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

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


            var eventType = event[1];
            if (eventType == 2) {
                app.CurrentView.matchList.updateMinutes();
                continue;
            }

            var matchId = event[2];
            var homeScore = event[5];
            var awayScore = event[6];
            var matchState = event[9];
            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 });
            }

        }
    }
});



