(function() {
    const Cu = Components.utils;
    var ns = MOA.ns('LM4.baiduAppHelper');
    const 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, "logger", function() {
        return new jsm.utils.logger("LM4.AppCenter.BaiduInjector");
    });
    
    ns.init = function() {
        document.getElementById('appcontent').addEventListener('DOMContentLoaded', function(evt) {
            ns.injectBaiduAppHelper(evt);
        }, false);
    };
    
    ns.injectBaiduAppHelper = function(evt) {
        if (!jsm.utils.getPref('injectbaiduapp')) {
            return;
        }
        
        if (!evt.originalTarget instanceof HTMLDocument) {
            return;
        }
        
        var view = evt.originalTarget.defaultView;
        if (!view) {
            return;
        }
        
        // Onlye inject page in top level.
        if (view.top != view) {
            return;
        }
        
        // Check if host is the same as defined in the pref
        var baiduAppSites = jsm.utils.getPref('baiduappsites');
        jsm.logger.trace(baiduAppSites);
        if (view.document.location.hostname != baiduAppSites) {
            return;
        }
        
        jsm.logger.trace('inject baidu app page.');
        
        try {
            var baiduapp_js = jsm.utils.getContentFromURL('resource://livemargins/scripts/baidu.js'); 
            
            var sandbox = new Cu.Sandbox(view);
            sandbox.unsafeWindow = view.window.wrappedJSObject;
            sandbox.window = view;
            sandbox.document = sandbox.window.document;
            sandbox.baiduAppHelper = baiduAppHelper;
            sandbox.JSON = JSON;
            
            Cu.evalInSandbox(baiduapp_js, sandbox);
            
            view.addEventListener("unload", function() {
                for (var attr in sandbox) {
                    delete sandbox[attr];
                }
            }, false);
        } catch (e) {
            jsm.logger.error('baidu app: ' + e);
        }
    };
    
    var baiduAppHelper = {
        appExists: function(appUID) {
            return jsm.AppCenter.appExists(appUID);
        },
        
        openInAppCenter: 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);
        }
    };
    
    window.addEventListener("load", function() {
        window.setTimeout(ns.init, 1000);
        window.removeEventListener("load", arguments.callee, false);
    }, false);
})();