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

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


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

        $scope.grid = AdminsService.grid;

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

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

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

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

                    $scope.fields.username = $scope.admin.username;
                    $scope.fields.email = $scope.admin.email;
                    $scope.fields.lastName = $scope.admin.lastName;
                    $scope.fields.firstName = $scope.admin.firstName;
                    $scope.fields.middleName = $scope.admin.middleName;
                    $scope.fields.suffix = $scope.admin.suffix;
                    $scope.fields.nickname = $scope.admin.nickname;

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

        /** Modal Edit End **/


        /** Modal Delete Start **/

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

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

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

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

    }
]);


/**
 * Delete Modal
 */
FanSportsApp.controller('AdminDeleteModalController', [ '$scope', '$http', 'growl', '$modalInstance',
    function ($scope, $http, growl, $modalInstance) {

        $scope.form = {};

        $scope.isSubmitted = false;

        if ($scope.admin.id != undefined && $scope.admin.id > 0) {
            $scope.username = $scope.admin.username;
            $scope.email = $scope.admin.email;
            $scope.lastName = $scope.admin.lastName;
            $scope.firstName = $scope.admin.firstName;
            $scope.middleName = $scope.admin.middleName;
            $scope.suffix = $scope.admin.suffix;
            $scope.nickname = $scope.admin.nickname;
        }

        $scope.submit = function () {
            $http({
                method: 'DELETE',
                url   : SportsFanAdmin.basePath + '/admins/rest/' + $scope.admin.id
            }).then(function (data) {
                $scope.init.home();
                growl.success('Administrator has been deleted.');
                $modalInstance.dismiss('close');
            });
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };

    }
]);

/**
 * Service
 */
FanSportsApp.factory('AdminsService', [ '$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 + '/admins/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
    };
} ]);
