
app.Services.CompetitionService = app.Services.CompetitionService || {
    getGroups: function (callback, continentId) {

        var request = { "T": 107 };
        if (continentId) {
            request.cId = continentId;
        }

        app.Services.makeRequest(request, app.Services.CompetitionService.parseGroups, callback);
    },
    
    getLeaguesAndCupsByGroup: function(callback, groupId) {
        var request = { "T": 101, "G": groupId };
        app.Services.makeRequest(request, app.Services.CompetitionService.parseLeagues, callback);
    },
    
    getLeaguesByCup: function(callback, cupId, groupId) {
        var request = { "T": 102, "c": cupId, "G":groupId };
        app.Services.makeRequest(request, app.Services.CompetitionService.parseLeagues, callback);
    },

    parseGroups: function (data, request, callback) {
        var leagues = [];
        for (var i = 0; i < data.L.length; i++) {
            var leagueData = data.L[i];
            
            var league = new app.Models.LeagueModel({
                id: leagueData.i,
                name: leagueData.n,
                isCup: leagueData.iC == 1,
                isInBlacklist: (leagueData.ibl * 1) == 1,
                groupId: leagueData.g,
                hasStandings: leagueData.hS == 1
            });
            league.set("isSelected", Settings.isFavorite({ assetId: league.get("id"), assetType: 4 }));
            leagues.push(league);
        }
        var groups = [];
        for (var i = 0; i < data.A.length; i++) {
            var groupData = data.A[i];
            var group = new app.Models.GroupModel({
                groupId: groupData.id,
                type: groupData.t,
                name: groupData.n
            });
            groups.push(group);
        }

        callback({ groups: groups, leagues: leagues });
    },
    
    parseLeagues: function(data, request, callback) {
        var leagues = [];
        for (var i = 0; i < data.L.length; i++) {
            var leagueData = data.L[i];

            var league = new app.Models.LeagueModel({
                id: leagueData.i,
                name: leagueData.n,
                isCup: leagueData.iC == 1,
                isInBlacklist: (leagueData.ibl * 1) == 1,
                hasStandings: leagueData.hS == 1,
                cupLeagueId: leagueData.l || 0,
                group: request.G
                
            });
            league.set("isSelected", Settings.isFavorite({ assetId: league.get("id"), assetType: 4 }));
            leagues.push(league);
        }

        callback(leagues, request.G);
    }
};