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

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


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

        $scope.grid = WeeksService.grid;

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

        $scope.leagues = LeaguesService.grid;
        $scope.seasons = SeasonsService.grid;

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

        $scope.fields = {
            sport : {
                id: 0
            },
            league: {
                id: 0
            },
            season: {
                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.querySeasons = function (item) {
            $scope.seasons.queryString.f = 'f[league_id]=' + item.id;
            $scope.seasons.pagination.pageSize = 0;
            $scope.seasons.call();
        };


        /** Modal Add Start **/

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

        $scope.modalAddActions = {
            show: function () {
                $scope.week = { 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 + '/weeks/html/edit',
            scope      : $scope,
            show       : false
        });

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

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

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

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

        /** Modal Edit End **/


        /** Modal Delete Start **/

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

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

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

        /** Modal Delete End **/

        $scope.endWeek = function (week) {
            var config = {
                method: 'PUT',
                url   : SportsFanAdmin.basePath + '/weeks/rest' + '/' + week,
                data : {
                    action: 'endweek'
                }
            };

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

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

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

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

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

    }
]);