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

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


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

        $scope.grid = TeamsService.grid;

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

        $scope.leagues = LeaguesService.grid;

        $scope.groups = GroupsService.grid;

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

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


        /** Modal Add Start **/

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

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

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

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

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

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

        /** Modal Edit End **/


        /** Modal Delete Start **/

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

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

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

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

    }
]);