/**
 * 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 + '/seasons/html/list'
        });

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


/**
 * Controller
 */
FanSportsApp.controller('SeasonsController', [ '$scope', '$rootScope', '$http', '$filter', '$modal', 'growl', 'SportsService', 'LeaguesService', 'SeasonsService',
    function ($scope, $rootScope, $http, $filter, $modal, growl, SportsService, LeaguesService, SeasonsService) {

        $scope.grid = SeasonsService.grid;

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

        $scope.leagues = LeaguesService.grid;

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

        $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();
        };


        /** Modal Add Start **/

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

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

        /** Modal Add End **/


        /** Modal Edit Start **/

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

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

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

                    $scope.fields.sport = $scope.season.sport;
                    $scope.fields.league = $scope.season.league;
                    $scope.fields.slug = $scope.season.slug;
                    $scope.fields.name = $scope.season.name;
                    $scope.fields.number = $scope.season.number;

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

        /** Modal Edit End **/


        /** Modal Delete Start **/

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

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

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

        /** Modal Delete End **/

        $scope.endSeason = function (season) {
            var config = {
                method: 'PUT',
                url   : SportsFanAdmin.basePath + '/seasons/rest' + '/' + season,
                data : {
                    action: 'endseason'
                }
            };

            $http(config).then(function success() {
                $scope.init.home();
                growl.success('Season has been ended');
            }, function failure() {
                growl.error('Failed to end the season');
            });
        };

        $scope.generateStandings = function (season) {
            var config = {
                method: 'PUT',
                url   : SportsFanAdmin.basePath + '/seasons/rest' + '/' + season,
                data : {
                    action: 'generatestandings'
                }
            };

            $http(config).then(function success() {
                $scope.init.home();
                growl.success('Standings for the Season has been generated');
            }, function failure() {
                growl.error('Failed to generate the standings for season');
            });
        };

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

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

            switch (method) {
                case 'DELETE':
                    config = {
                        method: 'DELETE',
                        url   : SportsFanAdmin.basePath + '/seasons/rest' + '/' + $scope.season.id
                    };
                    notifSuccess = 'Season has been deleted';
                    notifFailure = 'Failed to delete an Season.';
                    break;
                case 'POST':
                case 'PUT':
                default:
                    config = {
                        method: $scope.season.id > 0 ? 'PUT' : 'POST',
                        url   : SportsFanAdmin.basePath + '/seasons/rest' + ($scope.season.id > 0 ? ('/' + $scope.season.id) : ''),
                        data  : {
                            'sport-id'   : $scope.fields.sport.id,
                            'league-id'  : $scope.fields.league.id,
                            'slug'       : $scope.fields.slug,
                            'name'       : $scope.fields.name,
                            'number'     : $scope.fields.number
                        }
                    };
                    if ($scope.season.id > 0) {
                        notifSuccess = 'Season has been updated.';
                        notifFailure = 'Failed to update an Season.';
                    } else {
                        notifSuccess = 'Season has been added.';
                        notifFailure = 'Failed to add an Season';
                    }
            }

            $http(config).then(function success() {
                $scope.init.home();
                switch (method) {
                    case 'DELETE':
                        $scope.modalDeleteActions.hide();
                        break;
                    case 'POST':
                        $scope.modalAddActions.hide();
                        break;
                    case 'PUT':
                        $scope.modalEditActions.hide();
                        break;
                    default:
                        if ($scope.season.id > 0) {
                            $scope.modalEditActions.hide();
                        } else {
                            $scope.modalAddActions.hide();
                        }
                }
                growl.success(notifSuccess);
            }, function failure() {
                switch (method) {
                    case 'DELETE':
                        $scope.modalDeleteActions.hide();
                        break;
                    case 'POST':
                        $scope.modalAddActions.hide();
                        break;
                    case 'PUT':
                        $scope.modalEditActions.hide();
                        break;
                    default:
                        if ($scope.season.id > 0) {
                            $scope.modalEditActions.hide();
                        } else {
                            $scope.modalAddActions.hide();
                        }
                }
                growl.error(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();
            }
        };

    }
]);