'use strict';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            when('/Daybook', {templateUrl: '/partial/daybook.html', controller: DaybookCtrl, resolve: DaybookCtrl.resolve}).
            when('/Unposted', {templateUrl: '/partial/unposted.html', controller: UnpostedCtrl, resolve: UnpostedCtrl.resolve}).
            when('/ProfitLoss', {templateUrl: '/partial/profit-loss.html', controller: ProfitLossCtrl, resolve: ProfitLossCtrl.resolve}).
            when('/StockMovement', {templateUrl: '/partial/stock-movement.html', controller: StockMovementCtrl, resolve: StockMovementCtrl.resolve}).
            when('/NetTransactions', {templateUrl: '/partial/net-transactions.html', controller: NetTransactionsCtrl, resolve: NetTransactionsCtrl.resolve}).
            when('/PurchaseEntries', {templateUrl: '/partial/purchase-entries.html', controller: PurchaseEntriesCtrl, resolve: PurchaseEntriesCtrl.resolve}).
            when('/Purchases', {templateUrl: '/partial/purchases.html', controller: PurchasesCtrl, resolve: PurchasesCtrl.resolve}).
            when('/EmployeeFunctions', {templateUrl: '/partial/employee-functions.html', controller: EmployeeFunctionsCtrl}).

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

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

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

            when('/Accounts', {templateUrl: '/partial/account-list.html', controller: AccountListCtrl, resolve: AccountListCtrl.resolve}).
            when('/Account', {templateUrl: '/partial/account-detail.html', controller: AccountCtrl, resolve: AccountCtrl.resolve}).
            when('/Account/:id', {templateUrl: '/partial/account-detail.html', controller: AccountCtrl, resolve: AccountCtrl.resolve}).

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

            when('/CostCenters', {templateUrl: '/partial/cost-center-list.html', controller: CostCenterListCtrl, resolve: CostCenterListCtrl.resolve}).
            when('/CostCenter', {templateUrl: '/partial/cost-center-detail.html', controller: CostCenterCtrl, resolve: CostCenterCtrl.resolve}).
            when('/CostCenter/:id', {templateUrl: '/partial/cost-center-detail.html', controller: CostCenterCtrl, resolve: CostCenterCtrl.resolve}).

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

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

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

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

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

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

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

            otherwise({templateUrl: '/partial/404.html'});
        $locationProvider.html5Mode(true).hashPrefix('!');
    }])
    .config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    }])
    .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('BaseCtrl', ['$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 (typeof came_from === 'undefined' && $location.path() !== '/login') {
                came_from = $location.path();
            }
            $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;
        });
    });
}]);

