/**
 * Configuration
 */
FanSportsApp.config([ '$httpProvider', '$stateProvider', '$urlRouterProvider', '$locationProvider', function ($httpProvider, $stateProvider, $urlRouterProvider, $locationProvider) {
    $httpProvider.defaults.headers.common[ "X-Requested-With" ] = 'XMLHttpRequest';

    $stateProvider
        .state('home', {
            url        : '/',
            templateUrl: SportsFanPlayer.basePath + '/contests/html/list'
        })
        .state('contest', {
            url        : '/:con',
            templateUrl: SportsFanPlayer.basePath + '/contests/html/view'
        })
        .state('contest-join', {
            url        : '/:con/join',
            templateUrl: SportsFanPlayer.basePath + '/contests/html/join'
        });

    $urlRouterProvider.otherwise("/");

} ]);


/**
 * Controller
 */
FanSportsApp.controller('ContestsController', [
    '$scope', '$rootScope', '$http', '$state', '$stateParams', '$filter', '$modal', '$location', '$anchorScroll',
    'growl', 'SchedulesService', 'ContestsService', 'ContestsPlayersService', 'ContestsMixturesService', 'StandingsService',
    function ($scope, $rootScope, $http, $state, $stateParams, $filter, $modal, $location, $anchorScroll,
              growl, SchedulesService, ContestsService, ContestsPlayersService, ContestsMixturesService, StandingsService) {

        $scope.grid = ContestsService.grid;

        $scope.schedules = SchedulesService.grid;
        $scope.players = ContestsPlayersService.grid;
        $scope.mixtures = ContestsMixturesService.grid;
        $scope.standings = StandingsService.grid;
        
        $scope.contest = {
            id: 0
        };
        $scope.player = {};
        $scope.contestIsLoading = true;
        $scope.scheduleIsLoading = true;
        $scope.mixtureIsLoading = true;

        $scope.isSubmitting = false;

        $scope.models = {
            selected: null,
            matches : [],
            mixes   : []
        };
        
		$scope.standings.queryString.s = 's[percentage]=DESC';
        $scope.standings.queryString.g = '1';
        $scope.standings.pagination.pageSize = 0;
        
        $scope.rankings = {
        	'items': []
        };

        $scope.scrollTo = function(id) {
            $location.hash(id);
            $anchorScroll();
        };

        $scope.isCollapsed = false;


        $scope.betCount = 0;

        $scope.countBets = function () {
            return $scope.models.mixes.reduce(function (a, b) {
                return a + ((b['bet'] != undefined &&  b['bet'] != null && b['bet'] > 0) ? 1 : 0);
            }, 0);
        };

        $scope.dragOverReal = function (event, index, external, type) {
            return index < 1;
        };

        $scope.dropAtMixed = function (event, index, item) {
            return item;
        };

        $scope.setBet = function (index, id) {
            $scope.models.mixes[ index ].bet = id;
            $scope.betCount = $scope.countBets();
        };

        $scope.submitMixes = function () {
            $scope.isSubmitting = true;

            var data = {
                action   : 'join',
                contestId: $stateParams.con,
                mixes    : $scope.models.mixes
            };

            var result = ContestsService.actions.post(data);

            result.then(function () {
                growl.success('Contest joined. Results will be available after the last game of the week.');
                $scope.isSubmitting = false;
                $state.go('contest', { con: $stateParams.con }, { reload: true });
            }, function () {
                growl.success('Unable to join the contest.');
                $scope.isSubmitting = false;
            });
        };

        /** Modal Show Mixtures Start **/

        var modalMixtures = $modal({
            templateUrl: SportsFanPlayer.basePath + '/contests/html/mixtures',
            scope      : $scope,
            show       : false
        });

        $scope.modalMixturesActions = {
            show: function () {
                $http({
                    method: 'GET',
                    url   : SportsFanPlayer.basePath + '/contests/rest/' + $stateParams.con + '/players/' + SportsFanPlayer.currentUser.id
                }).then(function success(data) {
                    $scope.slot = data.data.response.data.entry;
                    $scope.slot.mixtures = [];

                    $http({
                        method: 'GET',
                        url   : SportsFanPlayer.basePath + '/contests/rest/' + $stateParams.con + '/players/' + SportsFanPlayer.currentUser.id + '/mixtures'
                    }).then(function success(data) {
                        $scope.slot.mixtures = data.data.response.data.entries;

                        modalMixtures.$promise.then(modalMixtures.show);
                    }, function failure(data) {
                        growl.error('Unable to retrieve Mixtures data.');
                    });

                }, function failure(data) {
                    growl.error('Unable to retrieve Slot data.');
                });


            },
            hide: function () {
                modalMixtures.$promise.then(modalMixtures.hide);
            }
        };

        /** Modal Show Mixtures End **/

        /** Modal Show Player Rankings Start **/

        var modalRankings = $modal({
            templateUrl: SportsFanPlayer.basePath + '/contests/html/rankings',
            scope      : $scope,
            show       : false
        });

        $scope.modalRankingsActions = {
            show: function () {
                $http({
                    method: 'GET',
                    url   : SportsFanPlayer.basePath + '/contests/rest/' + $stateParams.con + '/players?s[place]=ASC'
                }).then(function success(data) {
                    $scope.players.items = data.data.response.data.entries;
                    modalRankings.$promise.then(modalRankings.show);
                }, function failure(data) {
                    growl.error('Unable to retrieve Player data.');
                });
            },
            hide: function () {
                modalRankings.$promise.then(modalRankings.hide);
            }
        };

        /** Modal Show Player Rankings End **/

        $scope.init = {
            'home': function () {
                $scope.grid.queryString.q = '';
                $scope.grid.queryString.f = '';
                $scope.grid.queryString.s = '';
                $scope.grid.results.totalItems = null;
                $scope.grid.results.totalPages = null;
                $scope.grid.call();
            },
            'view': function () {
                $scope.contestIsLoading = true;
                $scope.scheduleIsLoading = true;
                $scope.mixtureIsLoading = true;

                var result = ContestsService.actions.get($stateParams.con);
                result.success(function (data) {
                    $scope.standings.call();

                    $scope.contest = data.response.data.entry;

                    $http({
                        method: 'GET',
                        url   : SportsFanPlayer.basePath + '/contests/rest/' + $stateParams.con + '/players?s[id]=ASC'
                    }).then(function success(data) {
                        $scope.players.items = data.data.response.data.entries;
                    }, function failure(data) {
                        growl.error('Unable to retrieve Player data.');
                    });
                    
                    $http({
                        method: 'GET',
                        url   : SportsFanPlayer.basePath + '/contests/rest/' + $stateParams.con + '/players?s[place]=ASC'
                    }).then(function success(data) {
                        $scope.rankings.items = data.data.response.data.entries;
                    }, function failure(data) {
                        growl.error('Unable to retrieve Rankings data.');
                    });

                    var playerPromise = ContestsPlayersService.actions.get($stateParams.con, SportsFanPlayer.currentUser.id);
                    playerPromise.then(function (data) {
                        $scope.player = data.data.response.data.entry;
                    });

                    $scope.models = {
                        selected: null,
                        matches : [],
                        mixes   : []
                    };

                    $scope.schedules.queryString.f = 'f[week_id]=' + $scope.contest.week.id;
                    var promise1 = $scope.schedules.promiseCall();

                    promise1.then(function (data) {
                        angular.forEach(data.data.response.data.entries, function (value) {
                            var teamsReal = {
                                home: [ {
                                    id   : value.homeTeam.id,
                                    name : value.homeTeam.name,
                                    group: value.homeTeam.groupId,
                                    type : 'home'
                                } ],
                                away: [ {
                                    id   : value.awayTeam.id,
                                    name : value.awayTeam.name,
                                    group: value.awayTeam.groupId,
                                    type : 'away'
                                } ]
                            };
                            $scope.models.matches.push(teamsReal);
                        });

                        $scope.contestIsLoading = false;
                    });


                    $scope.mixtures.contest = $scope.contest.id;
                    $scope.mixtures.player = SportsFanPlayer.currentUser.id;
                    var promise2 = $scope.mixtures.promiseCall();

                    promise2.then(function (data) {
                        angular.forEach(data.data.response.data.entries, function (value) {
                            var teamsMix = {
                                home: [ {
                                    id   : value.homeTeam.id,
                                    name : value.homeTeam.name,
                                    group: value.homeTeam.groupId,
                                    type : value.homeTeamSide
                                } ],
                                away: [ {
                                    id   : value.awayTeam.id,
                                    name : value.awayTeam.name,
                                    group: value.awayTeam.groupId,
                                    type : value.awayTeamSide
                                } ],
                                bet : {
                                    id   : value.bet.id,
                                    name : value.bet.name,
                                    group: value.bet.groupId
                                }
                            };
                            $scope.models.mixes.push(teamsMix);
                        });

                        $scope.contestIsLoading = false;
                    });


                }).error(function () {
                    growl.error('Failed to load Contest.');
                    $scope.contestIsLoading = false;
                });
            },
            'join': function () {

                $scope.models = {
                    selected: null,
                    matches : [],
                    mixes   : []
                };

                $scope.contestIsLoading = true;
                var result = ContestsService.actions.get($stateParams.con);

                result.success(function (data) {
                    $scope.standings.call();

                    $scope.contest = data.response.data.entry;

                    $http({
                        method: 'GET',
                        url   : SportsFanPlayer.basePath + '/contests/rest/' + $stateParams.con + '/players?s[id]=ASC'
                    }).then(function success(data) {
                        $scope.players.items = data.data.response.data.entries;
                    }, function failure(data) {
                        growl.error('Unable to retrieve Player data.');
                    });                    

                    $scope.schedules.queryString.f = 'f[week_id]=' + $scope.contest.week.id;
                    var promise = $scope.schedules.promiseCall();

                    promise.then(function (data) {
                        angular.forEach(data.data.response.data.entries, function (value) {
                            var teamsReal = {
                                home: [ {
                                    id   : value.homeTeam.id,
                                    name : value.homeTeam.name,
                                    group: value.homeTeam.groupId,
                                    type : 'home'
                                } ],
                                away: [ {
                                    id   : value.awayTeam.id,
                                    name : value.awayTeam.name,
                                    group: value.awayTeam.groupId,
                                    type : 'away'
                                } ]
                            };
                            var teamsBlank = {
                                home: [],
                                away: [],
                                bet : null
                            };
                            $scope.models.matches.push(teamsReal);
                            $scope.models.mixes.push(teamsBlank);
                        });

                        $scope.contestIsLoading = false;
                    });


                }).error(function () {
                    growl.error('Failed to load Contest.');
                    $scope.contestIsLoading = false;
                });
            }
        };

    }
]);


FanSportsApp.run(['$anchorScroll', function ($anchorScroll) {
    $anchorScroll.yOffset = 200;
}]);