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

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


/**
 * Controller
 */
FanSportsApp.controller('PlayersController', [ '$scope', '$rootScope', '$http', '$modal', 'growl', 'PlayersService',
    function ($scope, $rootScope, $http, $modal, growl, PlayersService) {

        $scope.grid = PlayersService.grid;

        $scope.player = { id: 0 };

        $scope.fields = {};

        $scope.searchAction = {
            search: function (keywords) {
                $scope.grid.queryString.q = keywords;
                $scope.grid.call();
                return $scope.grid.items;
            }
        };


        /** Modal Add Start **/

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

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

        /** Modal Add End **/


        /** Modal End Start **/

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

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

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

                    $scope.fields.username = $scope.player.username;
                    $scope.fields.email = $scope.player.email;
                    $scope.fields.lastName = $scope.player.lastName;
                    $scope.fields.firstName = $scope.player.firstName;
                    $scope.fields.middleName = $scope.player.middleName;
                    $scope.fields.suffix = $scope.player.suffix;
                    $scope.fields.nickname = $scope.player.nickname;
                    $scope.fields.birthdate = $scope.player.birthdate.date.normal;

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

        /** Modal Edit End **/


        /** Modal Delete Start **/

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

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

                    modalDelete.$promise.then(modalDelete.show);
                }, function failure(data) {
                    growl.error('Unable to retrieve Player 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 + '/players/rest' + '/' + $scope.player.id
                    };
                    notifSuccess = 'Player has been deleted';
                    notifFailure = 'Failed to delete an Player.';
                    break;
                case 'POST':
                case 'PUT':
                default:
                    config = {
                        method: $scope.player.id > 0 ? 'PUT' : 'POST',
                        url   : SportsFanAdmin.basePath + '/players/rest' + ($scope.player.id > 0 ? ('/' + $scope.player.id) : ''),
                        data  : {
                            username  : $scope.fields.username,
                            password  : $scope.fields.password,
                            email     : $scope.fields.email,
                            lastName  : $scope.fields.lastName,
                            firstName : $scope.fields.firstName,
                            middleName: $scope.fields.middleName,
                            suffix    : $scope.fields.suffix,
                            nickname  : $scope.fields.nickname,
                            birthdate : $scope.fields.birthdate
                        }
                    };
                    if ($scope.player.id > 0) {
                        notifSuccess = 'Player has been updated.';
                        notifFailure = 'Failed to update an Player.';
                    } else {
                        notifSuccess = 'Player has been added.';
                        notifFailure = 'Failed to add an Player';
                    }
            }

            $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.player.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.player.id > 0) {
                            $scope.modalEditActions.hide();
                        } else {
                            $scope.modalAddActions.hide();
                        }
                }
                growl.success(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();
            }
        };

    }
]);

/**
 * Service
 */
FanSportsApp.factory('PlayersService', [ '$http', function ($http) {
    var Grid = {
        isLoading  : false,
        items      : [],
        queryString: {
            q: '',    // Query
            f: '',  // Filter
            s: ''   // Sort
        },
        pagination : {
            currentPage: 1,
            pageSize   : 20
        },
        results    : {
            totalItems: null,
            totalPages: null
        },
        call       : function () {
            var query = '';

            Grid.isLoading = true;

            query += 'q=' + Grid.queryString.q;
            query += Grid.queryString.f != '' ? ('&' + Grid.queryString.f) : '';
            query += Grid.queryString.s != '' ? ('&' + Grid.queryString.s) : '';
            query += Grid.pagination.pageSize > 0 ? '&l=' + Grid.pagination.pageSize : '';
            query += '&p=' + Grid.pagination.currentPage;

            $http({
                method: 'GET',
                url   : SportsFanAdmin.basePath + '/players/rest?' + query
            }).then(function (data) {
                Grid.items = data.data.response.data.entries;
                Grid.results = {
                    totalItems: data.data.response.data.pagination.totalItems,
                    totalPages: data.data.response.data.pagination.totalPages
                };
                Grid.isLoading = false;
            });
        },
        refresh    : function () {
            Grid.queryString = {
                q: '',
                f: '',
                s: ''
            };
            Grid.pagination = {
                currentPage: 1,
                pageSize   : 20
            };
            Grid.call();
        },
        selectPage : function () {
            Grid.call();
            return false;
        }
    };

    return {
        grid: Grid
    };
} ]);
