const CATEGORY = 'yoono-dekstop-cl';
const CONTRACT_ID = '@mozilla.org/commandlinehandler/general-startup;1?type=yoono-desktop-cl';


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const CLASS_ID = Components.ID('{430CA0E4-9D44-11DE-81DD-6E8055D89593}');

const Handler = {

uninstall : function () {
  Components.utils.import("resource://yoono/yoonoYEXTIF.js");
  Components.utils.import("resource://yoono/yoonoService.js");
  Components.utils.import("resource://yoono/yoonoLog.js");
  Components.utils.import("resource://yoono/yoonoDialogs.js");
  Components.utils.import("resource://yoono/yoonoUtils.js");
  Components.utils.import("resource://yoono/yoonoPrefs.js");
  Components.utils.import("resource://yoono/yoonoSidebarService.js");
  Components.utils.import("resource://yoono/yoonoStorage.js");
  Components.utils.import("resource://yoono/yoonoKeyValueDB.js");
  
  Components.utils.reportError("uninstall ... ");
  var yoono = {};
  yoono.log=YOONO_LOG;
  yoono.utils=YOONO_UTILS;
  yoono.server = {
    launch : function (a,b) {
      // Called by YEXTIF when user is registered
      // with arguments ("connect", "no-sync")
      dump("Try to call launch with args : "+a+','+b+'\n');
    }
  }
  yoono.prefs=YOONO_PREFS;
  yoono.yextif=YOONO_YEXTIF;
  yoono.sidebar=YOONO_SIDEBAR;
  
  yoono.main=YOONO_CMPT;
  yoono.bkm = {start:function(){}};
  yoono.dialogs=YOONO_DIALOGS;
  yoono.storage=YOONO_STORAGE;
  
  YOONO_LOG.init(yoono);
  YOONO_PREFS.init(yoono);
  YOONO_DIALOGS.init(yoono);
  YOONO_CMPT.init(yoono);
  YOONO_SIDEBAR.init(YOONO_CMPT);
  YOONO_YEXTIF.init(yoono);
  YOONO_STORAGE.init(yoono);
  
  // Change YEXTIF specifics methods dynamically
  YOONO_YEXTIF.methods.isStandalone = function () {return 1;};
  YOONO_YEXTIF.methods.getClientType = function () {return "dsk";};
  YOONO_YEXTIF.methods.getVersion = function () {
    var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
    return appInfo.version;
  };

  // Open uninstall dialog
  var goodbyeWizardReturnObject={};
  var array = Components.classes["@mozilla.org/array;1"]
                        .createInstance(Components.interfaces.nsIMutableArray);
  var variant = Components.classes["@mozilla.org/variant;1"]
                          .createInstance(Components.interfaces.nsIWritableVariant);
  variant.setFromVariant(goodbyeWizardReturnObject);
  array.appendElement(variant, false);
  var windowWatcher = Cc['@mozilla.org/embedcomp/window-watcher;1']
          .getService(Ci.nsIWindowWatcher);
  windowWatcher.openWindow(
      null, 'chrome://yoono/content/dialogs/goodbye.xul',
      'navigator:browser', 'chrome,resizable=yes,dialog=yes,titlebar=yes,modal=yes', array)
  
  if (!goodbyeWizardReturnObject.value) return Components.utils.reportError("... uninstall canceled!");;
  
  var serverurl = YOONO_PREFS.get('serverurl');
  
  // Send uninstall request
  try {
    var script = goodbyeWizardReturnObject.script;
    var reqResult = YOONO_CMPT.sendRequest(serverurl + 'linkserver', 'POST', 'sync', script, null);
    
    var response = reqResult[1];
    var message = response['display-error'].@code;
    if('ERROR_INVALID_USER_ID' == message) {
    }
    message = response['display-message'].@code.toString();
    // TO BE DONE : what is best in case account could not be deleted ?
    switch(message) {
      case 'MSG_USER_ACCOUNT_REMOVED':
         // SUCCESSDELETED.hidden = false;
      break;
      case 'MSG_USER_ACCOUNT_NOT_REMOVED':
         // SUCCESSKEPT.hidden = false;
      break;
      default:
    }
  } catch(e) {
    Components.utils.reportError(e);
  }
  
  // Flush stats
  try {
    YOONO_CMPT.checkStats('uninstall');
  } catch(e) {
    Components.utils.reportError(e);
  }
  
  // Cleanup
  try {
    YOONO_CMPT.uninstall();
  } catch(e) {
    Components.utils.reportError(e);
  }
  
  Components.utils.reportError("... uninstall ok!");
},

QueryInterface: function(iid) {
    if(iid.equals(Ci.nsICommandLineHandler) ||
       iid.equals(Ci.nsIFactory) ||
       iid.equals(Ci.nsISupports))
        return this;

    throw Cr.NS_ERROR_NO_INTERFACE;
},

handle: function(cmdLine) {
  
  
  
  if(cmdLine.handleFlag('uninstall', false)) {
    
    this.uninstall();
    cmdLine.preventDefault = true;
    
  } else {
    
    var windowWatcher = Cc['@mozilla.org/embedcomp/window-watcher;1']
          .getService(Ci.nsIWindowWatcher);
    
    var windowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
        .getService(Ci.nsIWindowMediator);
    
    var window = windowMediator.getMostRecentWindow('navigator:browser');
    if(window)
      window.focus();
    else
      windowWatcher.openWindow(
            null, 'chrome://yoonorunner/content/main.xul',
            'navigator:browser', 'chrome,resizable=yes,titlebar=no', null);
    
  }
},

helpInfo: '-uninstall          Trigger uninstall process.\n',

createInstance: function(outer, iid) {
  if(outer != null)
    throw Cr.NS_ERROR_NO_AGGREGATION;

  return this.QueryInterface(iid);
},

lockFactory: function(lock) {
  /* no-op */
}

};


const Module = {
  QueryInterface: function(iid) {
    if(iid.equals(Ci.nsIModule) ||
       iid.equals(Ci.nsISupports))
        return this;

    throw Cr.NS_ERROR_NO_INTERFACE;
  },

  getClassObject: function(compMgr, cid, iid) {
    if(cid.equals(CLASS_ID))
      return Handler.QueryInterface(iid);

    throw Cr.NS_ERROR_NOT_REGISTERED;
  },

  registerSelf: function(compMgr, fileSpec, location, type) {
    compMgr.QueryInterface(Ci.nsIComponentRegistrar);
    compMgr.registerFactoryLocation(CLASS_ID, 'Handler', CONTRACT_ID, fileSpec, location, type);

    var catMan = Cc['@mozilla.org/categorymanager;1'].getService(Ci.nsICategoryManager);
    catMan.addCategoryEntry('command-line-handler', CATEGORY, CONTRACT_ID, true, true);
  },

  unregisterSelf: function mod_unreg(compMgr, location, type) {
    compMgr.QueryInterface(Ci.nsIComponentRegistrar);
    compMgr.unregisterFactoryLocation(CLASS_ID, location);

    var catMan = Cc['@mozilla.org/categorymanager;1'].getService(Ci.nsICategoryManager);
    catMan.deleteCategoryEntry('command-line-handler', CATEGORY);
  },

  canUnload: function (compMgr) {
    return true;
  }
};

function NSGetModule(comMgr, fileSpec) {
  return Module;
}
