'use strict';

var overlord = angular.module('overlord', ['overlord.directive', 'overlord.filter', 'overlord.service', 'ngCookies', 'ngRoute', 'ui.bootstrap', 'chieffancypants.loadingBar', 'ngMaterial'])
    .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {templateUrl: '/partial/home.html', controller: HomeController, resolve: HomeController.resolve}).
            when('/login', {templateUrl: '/partial/login.html', controller: LoginController}).
            when('/logout', {templateUrl: '/partial/home.html', controller: LogoutController}).

            when('/Journal', {
                templateUrl: '/partial/journal.html',
                controller: JournalController,
                resolve: JournalController.resolve
            }).
            when('/Journal/:id', {
                templateUrl: '/partial/journal.html',
                controller: JournalController,
                resolve: JournalController.resolve
            }).

            when('/Payment', {
                templateUrl: '/partial/payment.html',
                controller: PaymentController,
                resolve: PaymentController.resolve,
                reloadOnSearch: false
            }).
            when('/Payment/:id', {
                templateUrl: '/partial/payment.html',
                controller: PaymentController,
                resolve: PaymentController.resolve,
                reloadOnSearch: false
            }).

            when('/Receipt', {
                templateUrl: '/partial/receipt.html',
                controller: ReceiptController,
                resolve: ReceiptController.resolve,
                reloadOnSearch: false
            }).
            when('/Receipt/:id', {
                templateUrl: '/partial/receipt.html',
                controller: ReceiptController,
                resolve: ReceiptController.resolve,
                reloadOnSearch: false
            }).

            when('/Purchase', {
                templateUrl: '/partial/purchase.html',
                controller: PurchaseController,
                resolve: PurchaseController.resolve
            }).
            when('/Purchase/:id', {
                templateUrl: '/partial/purchase.html',
                controller: PurchaseController,
                resolve: PurchaseController.resolve
            }).

            when('/Return', {
                templateUrl: '/partial/purchase-return.html',
                controller: PurchaseReturnController,
                resolve: PurchaseReturnController.resolve
            }).
            when('/Return/:id', {
                templateUrl: '/partial/purchase-return.html',
                controller: PurchaseReturnController,
                resolve: PurchaseReturnController.resolve
            }).

            when('/Issue', {
                templateUrl: '/partial/issue.html',
                controller: IssueController,
                resolve: IssueController.resolve
            }).
            when('/Issue/:id', {
                templateUrl: '/partial/issue.html',
                controller: IssueController,
                resolve: IssueController.resolve
            }).

            when('/SalaryDeduction', {
                templateUrl: '/partial/salary-deduction.html',
                controller: SalaryDeductionController,
                resolve: SalaryDeductionController.resolve
            }).
            when('/SalaryDeduction/:id', {
                templateUrl: '/partial/salary-deduction.html',
                controller: SalaryDeductionController,
                resolve: SalaryDeductionController.resolve
            }).

            when('/ServiceCharge', {
                templateUrl: '/partial/employee-service-charge.html',
                controller: ServiceChargeController,
                resolve: ServiceChargeController.resolve
            }).
            when('/ServiceCharge/:id', {
                templateUrl: '/partial/employee-service-charge.html',
                controller: ServiceChargeController,
                resolve: ServiceChargeController.resolve
            }).

            when('/Ledger', {
                templateUrl: '/partial/ledger.html',
                controller: LedgerController,
                resolve: LedgerController.resolve
            }).
            when('/Ledger/:id', {
                templateUrl: '/partial/ledger.html',
                controller: LedgerController,
                resolve: LedgerController.resolve
            }).

            when('/Reconcile', {
                templateUrl: '/partial/reconcile.html',
                controller: ReconcileController,
                resolve: ReconcileController.resolve
            }).
            when('/Reconcile/:id', {
                templateUrl: '/partial/reconcile.html',
                controller: ReconcileController,
                resolve: ReconcileController.resolve
            }).

            when('/ProductLedger', {
                templateUrl: '/partial/product-ledger.html',
                controller: ProductLedgerController,
                resolve: ProductLedgerController.resolve
            }).
            when('/ProductLedger/:id', {
                templateUrl: '/partial/product-ledger.html',
                controller: ProductLedgerController,
                resolve: ProductLedgerController.resolve
            }).

            when('/CashFlow', {
                templateUrl: '/partial/cash-flow.html',
                controller: CashFlowController,
                resolve: CashFlowController.resolve
            }).
            when('/CashFlow/:id', {
                templateUrl: '/partial/cash-flow.html',
                controller: CashFlowController,
                resolve: CashFlowController.resolve
            }).

            when('/RawMaterialCost', {
                templateUrl: '/partial/raw-material-cost.html',
                controller: RawMaterialCostController,
                resolve: RawMaterialCostController.resolve
            }).
            when('/RawMaterialCost/:id', {
                templateUrl: '/partial/raw-material-cost-detail.html',
                controller: RawMaterialCostController,
                resolve: RawMaterialCostController.resolve
            }).

            when('/Attendance', {
                templateUrl: '/partial/attendance.html',
                controller: AttendanceController,
                resolve: AttendanceController.resolve
            }).
            when('/Attendance/:date', {
                templateUrl: '/partial/attendance.html',
                controller: AttendanceController,
                resolve: AttendanceController.resolve
            }).

            when('/EmployeeAttendance', {
                templateUrl: '/partial/employee-attendance.html',
                controller: EmployeeAttendanceController,
                resolve: EmployeeAttendanceController.resolve
            }).
            when('/EmployeeAttendance/:id', {
                templateUrl: '/partial/employee-attendance.html',
                controller: EmployeeAttendanceController,
                resolve: EmployeeAttendanceController.resolve
            }).

            when('/Daybook', {
                templateUrl: '/partial/daybook.html',
                controller: DaybookController,
                resolve: DaybookController.resolve
            }).
            when('/Unposted', {
                templateUrl: '/partial/unposted.html',
                controller: UnpostedController,
                resolve: UnpostedController.resolve
            }).
            when('/ProfitLoss', {
                templateUrl: '/partial/profit-loss.html',
                controller: ProfitLossController,
                resolve: ProfitLossController.resolve
            }).
            when('/StockMovement', {
                templateUrl: '/partial/stock-movement.html',
                controller: StockMovementController,
                resolve: StockMovementController.resolve
            }).
            when('/NetTransactions', {
                templateUrl: '/partial/net-transactions.html',
                controller: NetTransactionsController,
                resolve: NetTransactionsController.resolve
            }).
            when('/PurchaseEntries', {
                templateUrl: '/partial/purchase-entries.html',
                controller: PurchaseEntriesController,
                resolve: PurchaseEntriesController.resolve
            }).
            when('/Purchases', {
                templateUrl: '/partial/purchases.html',
                controller: PurchasesController,
                resolve: PurchasesController.resolve
            }).
            when('/EmployeeFunctions', {
                templateUrl: '/partial/employee-functions.html',
                controller: EmployeeFunctionsController
            }).

            when('/BalanceSheet', {
                templateUrl: '/partial/balance-sheet.html',
                controller: BalanceSheetController,
                resolve: BalanceSheetController.resolve
            }).
            when('/BalanceSheet/:date', {
                templateUrl: '/partial/balance-sheet.html',
                controller: BalanceSheetController,
                resolve: BalanceSheetController.resolve
            }).

            when('/TrialBalance', {
                templateUrl: '/partial/trial-balance.html',
                controller: TrialBalanceController,
                resolve: TrialBalanceController.resolve
            }).
            when('/TrialBalance/:date', {
                templateUrl: '/partial/trial-balance.html',
                controller: TrialBalanceController,
                resolve: TrialBalanceController.resolve
            }).

            when('/ClosingStock', {
                templateUrl: '/partial/closing-stock.html',
                controller: ClosingStockController,
                resolve: ClosingStockController.resolve
            }).
            when('/ClosingStock/:date', {
                templateUrl: '/partial/closing-stock.html',
                controller: ClosingStockController,
                resolve: ClosingStockController.resolve
            }).

            when('/Accounts', {
                templateUrl: '/partial/account-list.html',
                controller: AccountListController,
                resolve: AccountListController.resolve,
                reloadOnSearch: false
            }).
            when('/Account', {
                templateUrl: '/partial/account-detail.html',
                controller: AccountController,
                resolve: AccountController.resolve
            }).
            when('/Account/:id', {
                templateUrl: '/partial/account-detail.html',
                controller: AccountController,
                resolve: AccountController.resolve
            }).

            when('/Employees', {
                templateUrl: '/partial/employee-list.html',
                controller: EmployeeListController,
                resolve: EmployeeListController.resolve,
                reloadOnSearch: false
            }).
            when('/Employee', {
                templateUrl: '/partial/employee-detail.html',
                controller: EmployeeController,
                resolve: EmployeeController.resolve
            }).
            when('/Employee/:id', {
                templateUrl: '/partial/employee-detail.html',
                controller: EmployeeController,
                resolve: EmployeeController.resolve
            }).

            when('/CostCentres', {
                templateUrl: '/partial/cost-centre-list.html',
                controller: CostCentreListController,
                resolve: CostCentreListController.resolve
            }).
            when('/CostCentre', {
                templateUrl: '/partial/cost-centre-detail.html',
                controller: CostCentreController,
                resolve: CostCentreController.resolve
            }).
            when('/CostCentre/:id', {
                templateUrl: '/partial/cost-centre-detail.html',
                controller: CostCentreController,
                resolve: CostCentreController.resolve
            }).

            when('/Products', {
                templateUrl: '/partial/product-list.html',
                controller: ProductListController,
                resolve: ProductListController.resolve,
                reloadOnSearch: false
            }).
            when('/Product', {
                templateUrl: '/partial/product-detail.html',
                controller: ProductController,
                resolve: ProductController.resolve
            }).
            when('/Product/:id', {
                templateUrl: '/partial/product-detail.html',
                controller: ProductController,
                resolve: ProductController.resolve
            }).

            when('/Recipes', {
                templateUrl: '/partial/recipe-list.html',
                controller: RecipeListController,
                resolve: RecipeListController.resolve,
                reloadOnSearch: false
            }).
            when('/Recipe', {
                templateUrl: '/partial/recipe-detail.html',
                controller: RecipeController,
                resolve: RecipeController.resolve
            }).
            when('/Recipe/:id', {
                templateUrl: '/partial/recipe-detail.html',
                controller: RecipeController,
                resolve: RecipeController.resolve
            }).

            when('/ProductGroups', {
                templateUrl: '/partial/product-group-list.html',
                controller: ProductGroupListController,
                resolve: ProductGroupListController.resolve
            }).
            when('/ProductGroup', {
                templateUrl: '/partial/product-group-detail.html',
                controller: ProductGroupController,
                resolve: ProductGroupController.resolve
            }).
            when('/ProductGroup/:id', {
                templateUrl: '/partial/product-group-detail.html',
                controller: ProductGroupController,
                resolve: ProductGroupController.resolve
            }).

            when('/Users', {
                templateUrl: '/partial/user-list.html',
                controller: UserListController,
                resolve: UserListController.resolve
            }).
            when('/User', {
                templateUrl: '/partial/user-detail.html',
                controller: UserController,
                resolve: UserController.resolve
            }).
            when('/User/:id', {
                templateUrl: '/partial/user-detail.html',
                controller: UserController,
                resolve: UserController.resolve
            }).

            when('/Groups', {
                templateUrl: '/partial/group-list.html',
                controller: GroupListController,
                resolve: GroupListController.resolve
            }).
            when('/Group', {
                templateUrl: '/partial/group-detail.html',
                controller: GroupController,
                resolve: GroupController.resolve
            }).
            when('/Group/:id', {
                templateUrl: '/partial/group-detail.html',
                controller: GroupController,
                resolve: GroupController.resolve
            }).

            when('/Clients', {
                templateUrl: '/partial/client-list.html',
                controller: ClientListController,
                resolve: ClientListController.resolve
            }).
            when('/Client/:id', {
                templateUrl: '/partial/client-detail.html',
                controller: ClientController,
                resolve: ClientController.resolve
            }).

            when('/Message', {
                templateUrl: '/partial/message-detail.html',
                controller: MessageController,
                resolve: MessageController.resolve
            }).
            when('/Message/:id', {
                templateUrl: '/partial/message-detail.html',
                controller: MessageController,
                resolve: MessageController.resolve
            }).

            when('/Settings', {
                templateUrl: '/partial/settings.html',
                controller: SettingsController,
                resolve: SettingsController.resolve
            }).

            otherwise({templateUrl: '/partial/404.html'});
        $locationProvider.html5Mode(true).hashPrefix('!');
    }])
    .config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    }])
    .config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
        $mdDateLocaleProvider.formatDate = function (date) {
            return !angular.isUndefined(date) ? moment(date).format('DD-MMM-YYYY') : "";
        };
        $mdDateLocaleProvider.parseDate = function (date) {
            return moment(date, 'DD-MMM-YYYY').toDate();
        };
    }])
    .config(['$controllerProvider', function ($controllerProvider) {
        $controllerProvider.allowGlobals();
    }])
    .config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('responseInterceptor');
    }])
    .factory('responseInterceptor', ['$q', '$rootScope', function ($q, $rootScope) {
        return {
            response: function (response) {
                return response;
            },
            responseError: function (response) {
                var headers = response.headers(),
                    isResourceResponse = headers['content-type'] === "application/json; charset=utf-8",
                    status = response.status;
                if (status === 401 && !isResourceResponse) {
                    $rootScope.$broadcast('loginRequired');
                }
                // otherwise
                return $q.reject(response);
            }
        };
    }]);

overlord.controller('BaseController', ['$rootScope', '$scope', 'Auth', '$location', '$routeParams', function ($rootScope, $scope, Auth, $location, $routeParams) {
    $rootScope.$on('loginRequired', function () {
        if ($rootScope.auth.isAuthenticated) {
            $location.path('/');
        } else {
            var came_from = $routeParams.came_from;
            if (angular.isUndefined(came_from) && $location.path() !== '/login') {
                came_from = $location.url();
            }
            $location.path('/login').search({came_from: came_from});
        }
    });
    $scope.toasts = [];
    $scope.clearToast = function (item) {
        var idx = $scope.toasts.indexOf(item);
        if (idx !== -1) {
            $scope.toasts.splice(idx, 1);
        }
    };

    $rootScope.$on("$routeChangeStart", function (event, next, current) {
        Auth.get(function (u, putResponseHeaders) {
            $rootScope.auth = u;
            $rootScope.perms = u.perms;
        });
    });
}]);

