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

    $stateProvider
        .state('home', {
            url        : '/',
            templateUrl: SportsFanPlayer.basePath + '/schedules/html/list'
        });

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


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

        $scope.grid = SchedulesService.grid;

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

        $scope.leagues = LeaguesService.grid;

        $scope.schedule = {
            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: SportsFanPlayer.basePath + '/schedules/html/add',
            scope      : $scope,
            show       : false
        });

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

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

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

                    $scope.fields.sport = $scope.schedule.sport;
                    $scope.fields.league = $scope.schedule.league;
                    $scope.fields.slug = $scope.schedule.slug;
                    $scope.fields.name = $scope.schedule.name;
                    $scope.fields.shortName = $scope.schedule.shortName;
                    $scope.fields.description = $scope.schedule.description;

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

        /** Modal Edit End **/


        /** Modal Delete Start **/

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

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

                    modalDelete.$promise.then(modalDelete.show);
                }, function failure(data) {
                    growl.error('Unable to retrieve Schedule 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   : SportsFanPlayer.basePath + '/schedules/rest' + '/' + $scope.schedule.id
                    };
                    notifSuccess = 'Schedule has been deleted';
                    notifFailure = 'Failed to delete an Schedule.';
                    break;
                case 'POST':
                case 'PUT':
                default:
                    config = {
                        method: $scope.schedule.id > 0 ? 'PUT' : 'POST',
                        url   : SportsFanPlayer.basePath + '/schedules/rest' + ($scope.schedule.id > 0 ? ('/' + $scope.schedule.id) : ''),
                        data  : {
                            'sport-id'   : $scope.fields.sport.id,
                            'league-id'  : $scope.fields.league.id,
                            'slug'       : $scope.fields.slug,
                            'name'       : $scope.fields.name,
                            'short-name' : $scope.fields.shortName,
                            'description': $scope.fields.description
                        }
                    };
                    if ($scope.schedule.id > 0) {
                        notifSuccess = 'Schedule has been updated.';
                        notifFailure = 'Failed to update an Schedule.';
                    } else {
                        notifSuccess = 'Schedule has been added.';
                        notifFailure = 'Failed to add an Schedule';
                    }
            }

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

    }
]);