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

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


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

        $scope.grid = GroupsService.grid;

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

        $scope.leagues = LeaguesService.grid;

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

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

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

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

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

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

        /** Modal Edit End **/


        /** Modal Delete Start **/

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

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

                    modalDelete.$promise.then(modalDelete.show);
                }, function failure(data) {
                    growl.error('Unable to retrieve Group 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 + '/groups/rest' + '/' + $scope.group.id
                    };
                    notifSuccess = 'Group has been deleted';
                    notifFailure = 'Failed to delete an Group.';
                    break;
                case 'POST':
                case 'PUT':
                default:
                    config = {
                        method: $scope.group.id > 0 ? 'PUT' : 'POST',
                        url   : SportsFanAdmin.basePath + '/groups/rest' + ($scope.group.id > 0 ? ('/' + $scope.group.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.group.id > 0) {
                        notifSuccess = 'Group has been updated.';
                        notifFailure = 'Failed to update an Group.';
                    } else {
                        notifSuccess = 'Group has been added.';
                        notifFailure = 'Failed to add an Group';
                    }
            }

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

    }
]);