var coreWebApp = angular.module('coreWebApp', [
<% block dependencies %>
    'ngRoute',
    'ngAnimate',
    'ngSanitize',
    'kendo.directives',
    'restangular',
    'ngCkeditor',
    'ngDragDrop',
    'ui.sortable',
    'flow',
    'ngDialog',
<% endblock %>
    <% if modules %><% for module in modules %>, '<%= module %>Module'<% endfor %><% endif %>
], ['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
    $locationProvider.html5Mode(true);
    //$routeProvider.otherwise({ redirectTo: '<%= path({}, "admin") %>' });
    $routeProvider.otherwise({ redirectTo: '<%= path({"module": "sitemap", "controller": "list"}, "admin") %>' });
}]);

coreWebApp.modules = {};
coreWebApp.resolvables = {};

<% block config %>
    <% block config_auth %>
    coreWebApp.config(['AuthProvider', function (AuthProvider) {
        AuthProvider.setConfig({
            url: '<%= url({"action": "dialog"}, "oauth") %>',
            clientId: '<%= app.getConfig().app.oauth.client_id %>'
        });
    }]);
    <% endblock config_auth %>

    <% block config_heartbeat %>
    coreWebApp.config(['HeartbeatProvider', function (HeartbeatProvider) {
        HeartbeatProvider.setConfig({
            url: '<%= url({"action": "heartbeat"}, "auth") %>'
        });
    }]);
    <% endblock config_heartbeat %>

    <% block config_restangular %>
    coreWebApp.config(['RestangularProvider', function (RestangularProvider) {

        RestangularProvider.setBaseUrl('<%= url({}, "api") %>');
        RestangularProvider.setFullResponse(true);
        RestangularProvider.setRequestSuffix('/');
/*
        RestangularProvider.addResponseInterceptor(function (response, method, name, path) {

            if (method.toUpperCase() == 'PATCH') {
                Message.waitEnd();
            }

            var appModule = location.pathname.split('/admin/')[1].split('/')[0];
            var apiModule = path.split('/api/')[1].split('/')[0];

            if (appModule == apiModule) {
                angular.element('html').removeClass('is-contentLoading');
            }

            var newResponse = response;

            if (angular.isArray(response)) {
                newResponse.originalElement = [];
                angular.forEach(newResponse, function (value, key) {
                    newResponse.originalElement.push(angular.copy(value));
                });
            } else {
                newResponse.originalElement = angular.copy(response);
            }

            return newResponse;
        });

        RestangularProvider.setErrorInterceptor(function (error) {

            var appModule = location.pathname.split('/admin/')[1].split('/')[0];
            var apiModule = error.config.url.split('/api/')[1].split('/')[0];

            if (appModule == apiModule) {
                angular.element('html').removeClass('is-contentLoading');
            }
            
            if (error.status == 404) {
                
            }

            if (error.data && error.data.length && angular.isString(error.data[0])) {
                Message.error(error.data[0]);
                return false;
            }

        });
*/
    }]);
    <% endblock config_restangular %>

    <% block config_item_types %>
    coreWebApp.config(['ItemTypesProvider', function (ItemTypesProvider) {
        ItemTypesProvider.setType('article', 'cf-item-article');
        // ItemTypesProvider.setType('image', 'cf-item-image', {cover: 'Variation.admin_small'});
    }]);
    <% endblock config_item_types %>
    <% block config_delegate %>
    coreWebApp.config(['$sceDelegateProvider', function($sceDelegateProvider) {
        $sceDelegateProvider.resourceUrlWhitelist(['**']);
    }]);
    coreWebApp.config(['$sceDelegateProvider', '$compileProvider', function($sceDelegateProvider, $compileProvider) {
        $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file):|data:image\/|blob:/);
    }]);
    <% endblock config_delegate %>
<% endblock config %>

<% block run %>
    <% block run_main %>
    coreWebApp.run(['$rootScope', '$location', 'Auth', 'Heartbeat', 'Restangular', 'Message', 'Language', function ($rootScope, $location, Auth, Heartbeat, Restangular, Message, Language) {
        window.auth = Auth;
        Heartbeat.start();

        $rootScope.userManager = $rootScope.userManager || {
            userHasPrivilege: function () { return true; }
        };

        var authPromise = Auth.authorize();
        coreWebApp.resolvables.authorization = function () { return authPromise; };
        authPromise.then(function (data) {
            console.log('Auth: success');
            Restangular.setRequestInterceptor(function (element, method, name, path) {

                if (method.toUpperCase() == 'PATCH') {
                    Message.waitStart('Saving...');
                }

                Restangular.defaultHeaders['Authorization'] = 'Bearer ' + Auth.getToken(); // FIXME: bearer or Bearer?

                if ($rootScope.language) {
                    Restangular.defaultHeaders['Accept-Language'] = $rootScope.language;
                    Restangular.defaultHeaders['Content-Language'] = $rootScope.language;
                }

                return element;
            });
            Restangular.addResponseInterceptor(function (response, method, name, path) {

                if (method.toUpperCase() == 'PATCH') {
                    Message.waitEnd();
                }

                var appModule = location.pathname.split('/admin/')[1].split('/')[0];
                var apiModule = path.split('/api/')[1].split('/')[0];

                if (appModule == apiModule) {
                    angular.element('html').removeClass('is-contentLoading');
                }

                var newResponse = response;

                if (angular.isArray(response)) {
                    newResponse.originalElement = [];
                    angular.forEach(newResponse, function (value, key) {
                        newResponse.originalElement.push(angular.copy(value));
                    });
                } else {
                    newResponse.originalElement = angular.copy(response);
                }

                return newResponse;
            });

            Restangular.setErrorInterceptor(function (error) {

                Message.waitEnd();

                var appModule = location.pathname.split('/admin/')[1].split('/')[0];
                var apiModule = error.config.url.split('/api/')[1].split('/')[0];

                if (appModule == apiModule) {
                    angular.element('html').removeClass('is-contentLoading');
                }
                
                // if (error.status == 404) {
                    
                // }

                if (error && error.data && error.data.length) {
                    angular.forEach(error.data, function (item) {
                        Message.error(item.message);
                    });
                    // return false;
                }

            });
            Restangular.one('users', 'me').get().then(function (response) {
                $rootScope.currentUser = response.data.originalElement;
            });
        }, function (error) {
            console.log('Auth: error', error);
        });

        $rootScope.$on('$routeChangeStart', function() {
            angular.element('html').addClass('is-contentLoading');
            var params = $location.search();
            if (params.hasOwnProperty('language')) {
                if (params.language && params.language != Language.get()) {
                    Language.set(params.language);
                } else {
                    delete params.language;
                    $location.search(params);
                }
            }
        });
        $rootScope.$on('$routeChangeSuccess', function(a, b, c) {
            var appPath = $location.path().split('/admin/')[1].replace(/\/$/, '').split('/');
            if (appPath.length <= 1 || appPath[1] == 'create') {
                angular.element('html').removeClass('is-contentLoading');
            }
        });
    }]);
    <% endblock run_main %>
<% endblock run %>

<% block constants %>
    coreWebApp.constant('config', {
        domain:  'http://<%= app.get("request").hostname %>'
    });
<% endblock constants %>

<% block controllers %>
    <% block controllers_main %>
    coreWebApp.controller('MainController', ['$scope', '$window', 'Auth', 'Navigation', function ($scope, $window, Auth, Navigation) {
        Navigation.getFeature();
        $scope.logout = function (url) {
            Auth.revoke();
            $window.location.href = url;
        };
    }]);
    <% endblock controllers_main %>
    <% block controllers_nav %>
    coreWebApp.controller('NavController', ['$scope', '$location', function ($scope, $location) {
        $scope.isMenuItemActive = function (path) {
            return path === $location.path();
        };
    }]);
    <% endblock controllers_nav %>
<% endblock controllers %>
