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

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

    $urlRouterProvider.otherwise("/");
} ]);


/**
 * Controller
 */
FanSportsApp.controller('ContestsController', [ '$scope', '$rootScope', '$stateParams', '$http', '$filter', '$modal', 'growl',
    'SportsService', 'LeaguesService', 'WeeksService',
    'SchedulesService', 'ContestsService', 'ContestsSlotsService', 'ContestsMixturesService',
    function ($scope, $rootScope, $stateParams, $http, $filter, $modal, growl,
              SportsService, LeaguesService, WeeksService,
              SchedulesService, ContestsService, ContestsSlotsService, ContestsMixturesService) {

        $scope.grid = ContestsService.grid;

        $scope.sports = SportsService.grid;
        $scope.sports.call();

        $scope.leagues = LeaguesService.grid;

        $scope.weeks = WeeksService.grid;

        $scope.schedules = SchedulesService.grid;
        $scope.slots = ContestsSlotsService.grid;

        $scope.contest = {
            id: 0
        };
        $scope.contestIsLoading = true;
        $scope.scheduleIsLoading = true;
        $scope.mixtureIsLoading = true;

        $scope.isSubmitting = false;

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

        $scope.slot = {
            mixtures: []
        };

        $scope.fields = {
            sport : {
                id: 0
            },
            league: {
                id: 0
            }
        };

        $scope.searchAction = {
            search: function (keywords) {
                $scope.grid.queryString.q = keywords;
                $scope.grid.call();
                return $scope.grid.items;
            }
        };

        $scope.slugify = function () {
            $scope.fields.slug = $filter('fsaSlugify')($scope.fields.name);
        };

        $scope.queryLeagues = function (item) {
            $scope.leagues.queryString.f = 'f[sport_id]=' + item.id;
            $scope.leagues.pagination.pageSize = 0;
            $scope.leagues.call();
        };

        $scope.queryWeeks = function (item) {
            $scope.weeks.queryString.f = 'f[league_id]=' + item.id;
            $scope.weeks.queryString.s = 's[league_id]=ASC';
            $scope.weeks.pagination.pageSize = 0;
            $scope.weeks.call();
        };

        /** Modal Show Mixtures Start **/

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

        $scope.modalMixturesActions = {
            show: function (contestId, slotId) {
                $http({
                    method: 'GET',
                    url   : SportsFanAdmin.basePath + '/contests/rest/' + contestId + '/slots/' + slotId
                }).then(function success(data) {
                    $scope.slot = data.data.response.data.entry;
                    $scope.slot.mixtures = [];

                    $http({
                        method: 'GET',
                        url   : SportsFanAdmin.basePath + '/contests/rest/' + contestId + '/slots/' + slotId + '/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 Add Start **/

        var modalAdd = $modal({
            templateUrl: SportsFanAdmin.basePath + '/contests/html/add',
            scope      : $scope,
            show       : false
        });

        $scope.modalAddActions = {
            show: function () {
                $scope.contest = { id: 0 };
                $scope.fields = {};
                modalAdd.$promise.then(modalAdd.show);
            },
            hide: function () {
                modalAdd.$promise.then(modalAdd.hide);
            }
        };

        /** Modal Add End **/


        /** Modal End Start **/

        var modalEdit = $modal({
            templateUrl: SportsFanAdmin.basePath + '/contests/html/edit',
            scope      : $scope,
            show       : false
        });

        $scope.modalEditActions = {
            show: function (id) {
                $http({
                    method: 'GET',
                    url   : SportsFanAdmin.basePath + '/contests/rest/' + id
                }).then(function success(data) {
                    $scope.fields = {};

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

                    $scope.fields.name = $scope.contest.name;
                    $scope.fields.slug = $scope.contest.slug;
                    $scope.fields.description = $scope.contest.description;
                    $scope.fields.sport = $scope.contest.sport;
                    $scope.fields.league = $scope.contest.league;
                    $scope.fields.week = $scope.contest.week;
                    $scope.fields.minPlayers = $scope.contest.minPlayers;
                    $scope.fields.maxPlayers = $scope.contest.maxPlayers;
                    $scope.fields.entranceFee = $scope.contest.entranceFee;
                    $scope.fields.prize = $scope.contest.prize;

                    modalEdit.$promise.then(modalEdit.show);
                }, function failure(data) {
                    growl.error('Unable to retrieve Contest data.');
                });
            },
            hide: function () {
                modalEdit.$promise.then(modalEdit.hide);
            }
        };

        /** Modal Edit End **/

        /** Modal Reset Start **/

        var modalReset = $modal({
            templateUrl: SportsFanAdmin.basePath + '/contests/html/reset',
            scope      : $scope,
            show       : false
        });

        $scope.modalResetActions = {
            show: function (id) {
                $http({
                    method: 'GET',
                    url   : SportsFanAdmin.basePath + '/contests/rest/' + id
                }).then(function success(data) {
                    $scope.contest = data.data.response.data.entry;

                    modalReset.$promise.then(modalReset.show);
                }, function failure(data) {
                    growl.error('Unable to retrieve Contest data.');
                });
            },
            hide: function () {
                modalReset.$promise.then(modalReset.hide);
            }
        };

        /** Modal Reset End **/


        /** Modal Delete Start **/

        var modalDelete = $modal({
            templateUrl: SportsFanAdmin.basePath + '/contests/html/delete',
            scope      : $scope,
            show       : false
        });

        $scope.modalDeleteActions = {
            show: function (id) {
                $http({
                    method: 'GET',
                    url   : SportsFanAdmin.basePath + '/contests/rest/' + id
                }).then(function success(data) {
                    $scope.contest = data.data.response.data.entry;

                    modalDelete.$promise.then(modalDelete.show);
                }, function failure(data) {
                    growl.error('Unable to retrieve Contest data.');
                });
            },
            hide: function () {
                modalDelete.$promise.then(modalDelete.hide);
            }
        };

        /** Modal Delete End **/



        $scope.submit = function (method) {
            var config = {};

            var notifSuccess = '';
            var notifFailure = '';

            switch (method) {
                case 'DELETE':
                    config = {
                        method: 'DELETE',
                        url   : SportsFanAdmin.basePath + '/contests/rest' + '/' + $scope.contest.id
                    };
                    notifSuccess = 'Contest has been deleted';
                    notifFailure = 'Failed to delete an Contest.';
                    break;
                case 'RESET':
                    config = {
                        method: 'PUT',
                        url   : SportsFanAdmin.basePath + '/contests/rest' + ($scope.contest.id > 0 ? ('/' + $scope.contest.id) : ''),
                        data  : {
                            action: 'reset'
                        }
                    };
                    notifSuccess = 'Contest has been reset.';
                    notifFailure = 'Failed to reset a Contest.';
                    break;
                case 'POST':
                case 'PUT':
                default:
                    config = {
                        method: $scope.contest.id > 0 ? 'PUT' : 'POST',
                        url   : SportsFanAdmin.basePath + '/contests/rest' + ($scope.contest.id > 0 ? ('/' + $scope.contest.id) : ''),
                        data  : {
                            'action'      : $scope.contest.id > 0 ? 'add' : 'edit',
                            'name'        : $scope.fields.name,
                            'slug'        : $scope.fields.slug,
                            'description' : $scope.fields.description,
                            'sport-id'    : $scope.fields.sport.id,
                            'league-id'   : $scope.fields.league.id,
                            'week-id'     : $scope.fields.week.id,
                            'min-players' : $scope.fields.minPlayers,
                            'max-players' : $scope.fields.maxPlayers,
                            'entrance-fee': $scope.fields.entranceFee,
                            'prize'       : $scope.fields.prize
                        }
                    };
                    if ($scope.contest.id > 0) {
                        notifSuccess = 'Contest has been updated.';
                        notifFailure = 'Failed to update an Contest.';
                    } else {
                        notifSuccess = 'Contest has been added.';
                        notifFailure = 'Failed to add an Contest';
                    }
            }

            $http(config).then(function success() {
                $scope.init.home();
                switch (method) {
                    case 'RESET':
                        $scope.modalResetActions.hide();
                        break;
                    case 'DELETE':
                        $scope.modalDeleteActions.hide();
                        break;
                    case 'POST':
                        $scope.modalAddActions.hide();
                        break;
                    case 'PUT':
                        $scope.modalEditActions.hide();
                        break;
                    default:
                        if ($scope.contest.id > 0) {
                            $scope.modalEditActions.hide();
                        } else {
                            $scope.modalAddActions.hide();
                        }
                }
                growl.success(notifSuccess);
            }, function failure() {
                switch (method) {
                    case 'RESET':
                        $scope.modalResetActions.hide();
                        break;
                    case 'DELETE':
                        $scope.modalDeleteActions.hide();
                        break;
                    case 'POST':
                        $scope.modalAddActions.hide();
                        break;
                    case 'PUT':
                        $scope.modalEditActions.hide();
                        break;
                    default:
                        if ($scope.contest.id > 0) {
                            $scope.modalEditActions.hide();
                        } else {
                            $scope.modalAddActions.hide();
                        }
                }
                growl.success(notifFailure);
            });
        };

        $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.contest = data.response.data.entry;

                    $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,
                                    type: 'home'
                                } ],
                                away: [ {
                                    id  : value.awayTeam.id,
                                    name: value.awayTeam.name,
                                    type: 'away'
                                } ]
                            };
                            $scope.models.matches.push(teamsReal);
                        });

                        $scope.contestIsLoading = false;
                    });

                    $scope.slots.contest = $scope.contest.id;
                    $scope.slots.queryString.s = 's[place]=ASC';
                    $scope.slots.call();

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

    }
]);