(function () {
    'use strict';
    angular
        .module('app-base')
        .service('DrupalAppService', DrupalAppService)
        .service('DrupalBlocks', DrupalBlocks);

    /** @ngInject */
    function DrupalAppService($log,$window,AppSettings,AppService,AppData,Drupal) {
        var _this = this;

        this.initDrupalApp = function(options,callback){
            var config_file;
            var app_nid = options.app_nid;

            Drupal.init(options).then(init);

            function init(){
                if(options.standalone == true){
                    Drupal.baseUrl = "";
                }
                console.log('static = '+options.static);
                if(options.static == "true" && options.standalone == "true"){
                    config_file = Drupal.baseUrl+options.path_to_data+'/'+app_nid+'-settings.json';
                }else{
                    config_file = Drupal.baseUrl+'?q=appsettings/'+app_nid; // live appsettings
                }
                console.log('loading app settings: ... : '+config_file);

                config_file += '&rnd='+AppService.getUUID();
                AppSettings.get(config_file).then(function(settings){
                    var data_file;
                    Drupal.init(settings).then(function(){
                        console.log('update check: '+settings.changed+ ' > '+ Number(localStorage.getItem('app-'+app_nid+'-json-changed')));
                        if(settings.changed > Number(localStorage.getItem('app-'+app_nid+'-json-changed')) || localStorage.getItem('app-'+app_nid+'-json-changed') == null){
                            if(settings.static == "true"){
                                data_file = Drupal.baseUrl+'?q=app/'+settings.app_nid;
                            }else{
                                data_file = Drupal.baseUrl+'?q=app/'+settings.app_nid+'/update'; // live data update
                            }
                            if(settings.standalone == "true" && $window.location.protocol === 'file:'){
                                Drupal.path_to_data=settings.path_to_data.replace(Drupal.baseUrl,'')
                                Drupal.baseUrl = '';
                                data_file = settings.path_to_data+'/'+app_nid+'-data.json';
                            }else{
                                Drupal.file_directory_path = Drupal.baseUrl+settings.file_directory_path
                            }
                            console.log('loading app update: ... : '+data_file); // localStorage update
                            _this.getAppData(data_file,function(data){
                                callback.call(Drupal,data);
                            })
                        }else{
                            console.log('model up to date: using localStorage');
                            Drupal.model =  JSON.parse(localStorage.getItem('app-'+app_nid+'-json'));
                            callback.call(Drupal,Drupal.model);
                        }
                    })
                });
            }
        };

        this.getAppData = function(jsonUrl,callback) {
            var _this = this;
            if(jsonUrl.match('.jsonp')) {
                AppData.getJSONP(jsonUrl).then(function(data){
                    return parseData(data)
                });
            }else{
                jsonUrl += '&rnd='+AppService.getUUID();
                AppData.get(jsonUrl).then(function(data){
                    return parseData(data);
                });
            }
            function parseData(data){
                Drupal.model = Drupal.data  = data;
                // add views nodes to nodes collection
                for(var k in data.views){
                    if(k=='taxonomy_term'){
                        for(var n in data.views[k]){
                            for(var nn in data.views[k][n]){
                                Drupal.model.nodes[data.views[k][n][nn].nid] = data.views[k][n][nn]
                            }
                        }
                    }else{
                        for(var n in data.views[k]){
                            Drupal.model.nodes[data.views[k][n].nid] = data.views[k][n]
                        }
                    }
                }
                _this.saveLocalModel(Drupal.model,'app-'+data.appSettings.app_nid);
                return callback.call(Drupal,Drupal.model);
            }
        };

        this.saveLocalModel = function(model,modelName){
            var id = modelName || 'model';
            if($window.localStorage){
                $window.localStorage.setItem(id+'-json',JSON.stringify(model));
                if(model.appSettings) {
                    $window.localStorage.setItem(id + '-json-changed',model.appSettings.changed);
                }else{
                    $window.localStorage.setItem(id+'-json-changed',AppService.getTimeStamp());
                }
                $log.log("saveLocalModel() :: "+id+" :: "+ $window.localStorage.getItem(id+'-json-changed') )
            }
        }
    }

    // inline drupal ng_app module

    /** @ngInject */
    function DrupalBlocks($q,$log,$rootScope,$window,AppSettings,AppService,Drupal) {
        this.scopes = {};
        this.ready = false;
        this.init = function(scope){
            var _this = this;
            var defer = $q.defer();
            this.scopes[scope.delta] = scope;
            if(this.ready==true){
                defer.resolve();
            }else{
                AppSettings.domain = $rootScope.ng_app_domain;
                AppSettings.baseUrl = "http://"+$rootScope.ng_app_domain+"/";
                AppService.initialize({config_file: $rootScope.ng_app_config_file,scope:$rootScope}).then(function(){

                    var options = options;
                    options.domain = $rootScope.ng_app_domain; // inline url

                    Drupal.init(options).then(function(){
                        // Drupal.init({domain:$rootScope.ng_app_domain}).then(Drupal.connect).then(function(res){
                        Drupal.connect().then(function(){
                            if(AppSettings.ng_app_blocks){
                                _this.blocks = [];
                                var ng_app_blocks = AppSettings.ng_app_blocks;
                                for(var k in ng_app_blocks){
                                    for(var kk in ng_app_blocks[k]){
                                        _this.blocks.push(ng_app_blocks[k][kk]);
                                        $window.Drupal.settings[kk]={};
                                        $window.Drupal.settings[kk].model=ng_app_blocks[k][kk];
                                    }
                                }
                            }
                            $log.debug('app-base: init-blocks');
                            $rootScope.$broadcast('init-blocks',$rootScope);
                            _this.ready = true;
                            defer.resolve();
                        })
                    })
                });
            }
            return defer.promise;
        }
    }

})();