(function() {
    const Cu = Components.utils;
    
    var jsm = { };
    if (typeof XPCOMUtils == "undefined") {    
        Cu.import("resource://gre/modules/XPCOMUtils.jsm");
    }
    
    XPCOMUtils.defineLazyGetter(jsm, "utils", function() {
        let obj = { };
        Cu["import"]("resource://livemargins/utils.jsm", obj);
        return obj.utils;
    });
    
    XPCOMUtils.defineLazyGetter(jsm, "AppCenter", function() {
        let obj = { };
        Cu["import"]("resource://livemargins/appcenter.jsm", obj);
        return obj.AppCenter;
    });
    
    XPCOMUtils.defineLazyGetter(jsm, "AppCenterDAO", function() {
        let obj = { };
        Cu["import"]("resource://livemargins/dao.jsm", obj);
        return obj.AppCenterDAO;
    });
    
    XPCOMUtils.defineLazyGetter(jsm, "logger", function() {
        return new jsm.utils.logger("LM4.webAppManager");
    });
    
    var ns = MOA.ns('LM4.webAppManager');
    
    var appInstaller = {
        getVersion: function() {
            return jsm.AppCenter.version
        },
        
        appExists: function(appUID) {
            return jsm.AppCenter.appExists(appUID);
        },
        
        // install app without bookmark, and open it
        openApp: function(appInfo) {
            if (!appInfo || !appInfo.appUID) {
                throw new Error('Missing some arguments.');
            }
            
            if (!this.appExists(appInfo.appUID)) {
                jsm.AppCenter.installApp(appInfo);
            } 
            
            jsm.AppCenter.openApp(appInfo.appUID);
        },
        
        getMyLocalApps: function() {
            return jsm.AppCenterDAO.getAllNonBuiltInApps();
        },
        
        getLocalApp: function(uid) {
            return jsm.AppCenterDAO.getNonBuiltInAppByUID(uid);
        },
        
        checkLocal: function(uid, isLocal) {
            jsm.AppCenter.checkLocal(uid, isLocal);    
        }
    };

    ns.init = function() {
        var mainWindow = document.getElementById('appcontent');
        
        mainWindow.addEventListener('DOMContentLoaded', ns.injectAppManager, false);
    };
    
    ns.injectAppManager = function(evt) {
        if (!evt.originalTarget instanceof HTMLDocument) {
            return;
        }
        
        var view = evt.originalTarget.defaultView;
        if (!view) {
            return;
        }
        
        // Only inject page in three levels.
        if (view.top != view && view.top != view.parent && view.top != view.parent.parent) {
            return;
        }
        
        // Check if host is in domains defined in the pref.
        var canBeInjected = false;
        var strDomains = jsm.utils.getPref('appsites');
        var domains = strDomains.split(/\d*,\d*/);
        for (var i = 0; i < domains.length; i++) {
            if (view.document.location.protocol == 'about:') {
                continue;
            }
            
            if (jsm.utils.isChildDomain(view.document.location.hostname, domains[i])) {
                canBeInjected = true;
                break;
            }
        }
        
        if (!canBeInjected) {
            return;
        }
        
        jsm.logger.trace('inject location: ' + evt.originalTarget.defaultView.document.location.href);
        
        view.window.wrappedJSObject['appInstaller'] = appInstaller;
    };
    
    window.addEventListener('load', function() {
        window.setTimeout(ns.init, 1000);
        window.removeEventListener("load", arguments.callee, false);
    }, false);
})();