/*
 * Copyright (c) OutWit Technologies 2007-2017.
 * All rights reserved.
 */

var outwitDocs = {};

outwitDocs.onLoad = function(event) {
  if (window.owLoaded) {
    //Components.utils.reportError("owLoaded");
    outwitDocs.load(event);
  }
  else {
    //Components.utils.reportError("NOT owLoaded, setting load callback");
    window.owOnLoad = outwitDocs.load.bind(outwitDocs);
  }
};




outwitDocs.load = function OWDocsStartup(){
  try {
    ow.app.load();
  }
  catch(e) {
    ow.log.error("Error loading application", e);
  }

  ow.app.onUnload((function(anEvent) {
    anEvent.callback(true);
  }).bind(this));

  ow.app.onShutdown((function(anEvent) {
    try {
      gDownloadManager.removeProgressListener(gDownloadListener);
      gDownloadManager.unload(true);

      widgets.page.browserManager.removeEventListener("locationChanged", outwitDocs.extractControls.locationChangeListener);

      widgets.page.browserManager.removeEventListener("locationChanged", outwitDocs.locationChangeListener);

      widgets.page.browserManager.removeEventListener("allLinksExtracted", outwitDocs.allStoppedListener);
      widgets.page.browserPilot.removeEventListener("start", outwitDocs.pilotStartListener);
      widgets.page.browserPilot.removeEventListener("stop", outwitDocs.pilotStopListener);

      widgets.page.unload();

      // shutdown the kernel
      mainKit.shutdown();

      optionsCtrl.unload();

      //Remove the browser listenr
      unregisterListeners();
        
      //Stop the download hook
      //DownloadMonitorPanel.uninit();

      delete window.keepTitle;
    }
    catch(e) {
      ow.log.error("Shutdown error", e);
    }
    anEvent.callback();
  }).bind(this));


  mainKit.init();

  widgets.page.load(20000, 2500, 3500, true);

  gContainer  = document.getElementById('gFolder');
  gCatch      = document.getElementById("gCatch");
  outwitDocs.UIControls.URLBar = document.getElementById('urlbar');

  outwitDocs.extractControls.extractorManager = widgets.page.extractorManager;

//XXX  coreKit.coreMessager.subscribe(historyHandler._stackObserver, "BROWSE_stop");

  //outwitKit.networkHelpers.checkLine();
  mainKit.loadURI = function(anURL, aReferer) {
    historyHandler.newGo(anURL, null, null, aReferer);
  };


  widgets.page.extractorManager.registerDefault("documents");
  widgets.page.extractorManager.setAutoRun("documents", true);
  widgets.page.extractorManager.setSingleInstance("documents", false);


  widgets.page.browserManager.addEventListener("locationChanged", outwitDocs.extractControls.locationChangeListener);


  widgets.page.browserManager.addEventListener("locationChanged", outwitDocs.locationChangeListener);
  // XXX allLinksExtracted iznogoud. We should have an event on browserExtractorManager and use it instead.
  widgets.page.browserManager.addEventListener("allLinksExtracted", outwitDocs.allStoppedListener);
  widgets.page.browserPilot.addEventListener("start", outwitDocs.pilotStartListener);
  widgets.page.browserPilot.addEventListener("stop", outwitDocs.pilotStopListener);

  var browser = widgets.page.browser;
  // Prepare the browser rectriction
  browser.docShell.allowImages = false;
  browser.docShell.allowPlugins = false;
  browser.docShell.allowAuth = false;
  //browser.markupDocumentViewer.authorStyleDisabled = true;


  //waitForFullLoading();
  
  // Hook up the download manager
  //DownloadMonitorPanel.init();

  optionsCtrl.init();
  //optionsCtrl.autoBrowse = !kOW_DEBUGMODE; //don't bother us in debug mode
  

  document.getElementById("catchHeaderLengthLabel").setAttribute("value", gCatch.length);

  var catchLengthMutationObserver = new MutationObserver(function(mutations) {
    document.getElementById("catchHeaderLengthLabel").setAttribute("value", gCatch.length);
    document.getElementById("menuSaveCatch").setAttribute("disabled", gCatch.length == 0);
    document.getElementById("menuEmptyCatch").setAttribute("disabled", gCatch.length == 0);
  });
  catchLengthMutationObserver.observe(gCatch, { attributes: true, attributeFilter: ["length"] });


  document.getElementById("menuSaveCatch").setAttribute("disabled", gCatch.length == 0);
  document.getElementById("menuEmptyCatch").setAttribute("disabled", gCatch.length == 0);

  gDownloadManager = new coreKit.downloadManager(5);
  gDownloadListener = {
    _current: 0,
    _queued: 0,
    _updateStatus: function() {
      if (gNotification) {
        gNotification.dlCurrent.setAttribute('value', this._current);
        gNotification.dlQueued.setAttribute('value', this._queued);
        gNotification.dlMonitor.setAttribute('collapsed', !(this._queued + this._current));
      }
    },
    onEnqueue: function() {
      this._queued++;
      this._updateStatus();
    },
    onStart: function() {
      this._queued--;
      this._current++;
      this._updateStatus();
      dump("start\n");
    },
    onSuccess: function() {
      this._current--;
      this._updateStatus();
      dump("stop\n");
    },
    onFail: function() {
      this._current--;
      this._updateStatus();
      dump("fail\n");
    }
  };
  gDownloadManager.addProgressListener(gDownloadListener);

  registerListeners();

  // XXX bad
  outwitKit.engineTester.testData.words = coreKit.localeService.getString('searchEngineTestVoca', 'chrome://outwit-modules-docs/locale/main.properties').split(/ *, */);
  outwitDocs.gEngineManager = new outwitKit.engineManager("oWDocs.searchEnginesConfig", unregisterListeners, registerListeners);

  if (ow.app.kernel.prefs.getString('oWDocs.lastStartupVersion', "") != ow.app.module.version) {
    ow.app.kernel.prefs.setString('oWDocs.lastStartupVersion', ow.app.module.version);
    resetEngineConfig();
  }

  if (ow.app.kernel.prefs.getBool('oWDocs.allowEngineTest', true)) {
    historyHandler.pause = true;
		/*
		if (mainKit.originalURI) {
      historyHandler.newGo(mainKit.originalURI.toString());
		}
		*/
    function runAfterTesting() {
      historyHandler.pause = false;
    }
    outwitDocs.gEngineManager.runQuickTest(outwitDocs.gEngineManager.currentEngine, runAfterTesting);
  }
  else {
		/*
		if (mainKit.originalURI) {
			historyHandler.newGo(mainKit.originalURI.toString());
		}
		*/
  }


  if (!kOW_DEBUGMODE) {
    document.getElementById("viewAsSelect_" + "browser").setAttribute("hidden", "true");
    document.getElementById("viewAsMenu_" + "browser").setAttribute("hidden", "true");
  }

};


outwitDocs.UIControls = {};

outwitDocs.UIControls.URLBar = null;

var gContainer  = null;
var gCategory   = null;
var gCatch      = null;
var gDownloadManager = null;
var gDownloadListener = null;
outwitDocs.gEngineManager = null;

/*
 * Controller for the statusbar
 */
var gNotification = {
  get element(){
    return document.getElementById('statusBox');
  },
  defaultValue:'',
  get dlCurrent() {
    return document.getElementById('statusDlCurrent');
  },
  get dlQueued() {
    return document.getElementById('statusDlQueued');
  },
  get dlMonitor() {
    return document.getElementById('statusDownloadMonitor');
  },

  reset: function(){
    this.defaultValue = '';
    this.element.setAttribute('value', '');
  },
  show: function( aLabel ){
    this.defaultValue = aLabel;
    this.element.setAttribute('value', aLabel );
  },


  hide: function(){
    document.getElementById("statusBoxHelp").value = '';
    document.getElementById("statusBoxUrl").collapsed = false;
  },

  showHelp: function(){
    // set help
    let aBean = [];
    for(let i = 0 ; i<arguments.length ;i++){
      aBean.push( coreKit.localeService.getString(arguments[i], 'chrome://outwit-modules-docs/locale/help.properties') );
    }
    document.getElementById("statusBoxHelp").value = aBean.join("\n");
    document.getElementById("statusBoxUrl").collapsed = true;
  },

  showUrl: function(anUrl) {
    // set exploring + url
    document.getElementById("statusBoxUrl").value = (anUrl ? coreKit.localeService.getString('statusExploring', 'chrome://outwit-modules-docs/locale/main.properties') + ' ' + anUrl : '');
  },

  get notificationBox() {
    return document.getElementById("notificationBox");
  },

  hideAllNotifications: function() {
    this.hideTopNotificationManyNoResult();
    this.hideTopNotificationNoResult();
  },
  hideTopNotificationManyNoResult: function() {
    var previousNotification = this.notificationBox.getNotificationWithValue('manyNoResult');
    if (previousNotification) {
      this.notificationBox.removeNotification(previousNotification);
    }
  },

  showTopNotificationManyNoResult: function(engine) {
    try {
    var notificationText = coreKit.localeService.getString('manyNoResultNotificationLabel', 'chrome://outwit-modules-docs/locale/main.properties');

    notificationText = notificationText.replace("#engine#", engine);

    this.hideTopNotificationManyNoResult();

    var notif = this.notificationBox.appendNotification(
      notificationText,
      'manyNoResult',
      null,
      this.notificationBox.PRIORITY_WARNING_HIGH,
      [
        { 
          label: coreKit.localeService.getString('resetConfigLabel', 'chrome://outwit-modules-docs/locale/main.properties'),
          accessKey: '',
          callback: function(event) {
            outwitDocs.gEngineManager.resetConfig(engine);
          }
        },
        { 
          label: coreKit.localeService.getString('stopAskingLabel', 'chrome://outwit-modules-docs/locale/main.properties'),
          accessKey: '',
          callback: function(event) {
            outwitDocs.gEngineManager.setCheck(engine, false);
          }
        },
        { 
          label: coreKit.localeService.getString('cancelLabel', 'chrome://outwit-modules-docs/locale/main.properties'),
          accessKey: '',
          callback: function(event) {
          }
        }

      ]);
      notif.persistence = 2;
    }
    catch(e) {
      dump("showTopNotificationManyNoResult errror : " + e + "\n");
    }
  },

  hideTopNotificationNoResult: function() {
    var previousNotification = this.notificationBox.getNotificationWithValue('noResult');
    if (previousNotification) {
      this.notificationBox.removeNotification(previousNotification);
    }
  },
  showTopNotificationNoResult: function(aURL) {
    try {
    this.hideTopNotificationNoResult();

    var notificationText = "";
    var engine = gCategory.getEngine();
    if (engine) {
      if (outwitDocs.gEngineManager.incrementNoResult(engine) > 3
          && outwitDocs.gEngineManager.hasBestConfig(engine)
          && outwitDocs.gEngineManager.getCheck(engine)) {
        this.showTopNotificationManyNoResult(engine);
        return;
      }
      notificationText = coreKit.localeService.getString('noSearchResultNotificationLabel', 'chrome://outwit-modules-docs/locale/main.properties');
      notificationText = notificationText.replace("#search#", gCategory.getWords())
                                         .replace("#engine#", engine);
    }
    else {
      notificationText = coreKit.localeService.getString('noPageResultNotificationLabel', 'chrome://outwit-modules-docs/locale/main.properties');
      notificationText = notificationText.replace("#url#", (aURL ? aURL : gCategory.getUrl()));
    }

    if (ow.app.kernel.prefs.getString("oWDocs.queryTypesInQuery", "all") == "selectionPanel" 
        && !document.getElementById("fileFormat_any").checked) {
      notificationText += "\n" + coreKit.localeService.getString('haveFilterNotificationLabel', 'chrome://outwit-modules-docs/locale/main.properties');
    }

    var notif = this.notificationBox.appendNotification(
        notificationText,
        'noResult',
        null,
        this.notificationBox.PRIORITY_INFO_HIGH,
        []);
    notif.persistence = 1;
    }
    catch(e) {
      dump("showTopNotificationNoResult Error : " + e + "\n");
    }
  }

};


function resetEngineConfig() {
  outwitDocs.gEngineManager.resetConfig();
  gNotification.hideTopNotificationManyNoResult();
};


function currentSearchEngineChanged() {
  gNotification.hideTopNotificationManyNoResult();
  gNotification.hideTopNotificationNoResult();
  if (!historyHandler.lock && ow.app.kernel.prefs.getBool('oWDocs.allowEngineTest', true)) {
    historyHandler.pause = true;
    function runAfterTesting() {
      historyHandler.pause = false;
    }
    outwitDocs.gEngineManager.runQuickTest(outwitDocs.gEngineManager.currentEngine, runAfterTesting);
  }
}


function registerListeners() {
//XXX  gBrowser.addProgressListener(browserListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
//XXX  coreKit.coreMessager.subscribe(DocumentFeeder, 'Links', '*');

  /*
  coreKit.coreMessager.subscribe(searchTreeCtrl, "BROWSE_start");
  coreKit.coreMessager.subscribe(searchTreeCtrl, "BROWSE_stop");
  coreKit.coreMessager.subscribe(statusBoxUpdater, "BROWSE_start");
  coreKit.coreMessager.subscribe(statusBoxUpdater, "BROWSE_stop");
  */
};


function unregisterListeners() {
  try {
//XXX  gBrowser.removeProgressListener(browserListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
//XXX  coreKit.coreMessager.unsubscribe(DocumentFeeder, 'Links', '*');

    /*
  coreKit.coreMessager.unsubscribe(searchTreeCtrl, "BROWSE_start");
  coreKit.coreMessager.unsubscribe(searchTreeCtrl, "BROWSE_stop");
  coreKit.coreMessager.unsubscribe(statusBoxUpdater, "BROWSE_start");
  coreKit.coreMessager.unsubscribe(statusBoxUpdater, "BROWSE_stop");
  */
  }
  catch(e) {
    //dump(e + "\n"); 
  }
};



outwitDocs.locationChangeListener = function(event) {
  // starts throbber
  searchTreeCtrl.startThrobber();
  historyHandler.lock = true;
  statusBoxUpdater.onStartBrowse();
};

outwitDocs.pilotStartListener = function(event) {

};

outwitDocs.pilotStopListener = function(event) {
  // stops throbber if all stopped
  if (!widgets.page.running) {
    searchTreeCtrl.stopThrobber();
    historyHandler.lock = false;
    statusBoxUpdater.onStopBrowse();
    coreKit.timerService.setTimer(1, null, historyHandler._stackExec, historyHandler);
  }
};

outwitDocs.allStoppedListener = function(event) {
  // stops throbber if not browing
  if (!widgets.page.running) {
    searchTreeCtrl.stopThrobber();
    historyHandler.lock = false;
    statusBoxUpdater.onStopBrowse();
    coreKit.timerService.setTimer(1, null, historyHandler._stackExec, historyHandler);
  }

  // _stackExec si pas browsing
};




/*
function waitForFullLoading(){
  var thread =  Components.classes["@mozilla.org/thread-manager;1"]
                .getService(Components.interfaces.nsIThreadManager)
                .mainThread;
  while (! ( 
    gContainer.iconsview.browser.contentWindow.wrappedJSObject.Folder && 
    gContainer.listview.browser.contentWindow.wrappedJSObject.Folder
   ) ) thread.processNextEvent(true);
};
*/



var statusBoxUpdater = {
  onStartBrowse: function() {
    gNotification.showUrl(widgets.page.currentURI.spec);
  },
  onStopBrowse: function() {
    gNotification.showUrl('');

    if (gCategory && gCategory.length() == 0) {
      gNotification.showTopNotificationNoResult();
    }
  }
};
  

function toggleSidebarBox(){
  var splitter = document.getElementById('left-splitter');
  var state = splitter.getAttribute('state');
  if( state == 'collapsed' ){
    splitter.setAttribute('state', 'open');
    return true;
  }
  else{
    splitter.setAttribute('state', 'collapsed');
    return false;
  }
};



/*
 * Hook on select all to apply our custom handler for
 * the view area
 * XXX Should implement an internal hook
 */
function selectAll(){
  var focused = document.commandDispatcher.focusedElement;
  if( focused == null || 
      focused=='chrome://outwit-kernel/content/widgets/directory/icons/view.html' ||
      focused == '[object XPCNativeWrapper [object XULElement]]' ){ // for now we assume to do that on the html
    gContainer.selectAll();
  }
  else if (focused.getAttribute("id") == "gCatch") focused.selectAll();
  else goDoCommand('cmd_selectAll');
};

function viewBrowser() {
  document.querySelector("#mainDeck").selectedIndex = 1;

  var list = document.getElementById('modeListMenu');
  list.parentNode.selectedItem = document.getElementById("viewAsSelect_" + "browser");
  document.getElementById("viewAsMenu_" + "browser").setAttribute("checked", 'true');
}

function viewAs( aType ){
  var type = aType || "icons";
  document.querySelector("#mainDeck").selectedIndex = 0;
  var list = document.getElementById('modeListMenu');

  list.parentNode.selectedItem = document.getElementById("viewAsSelect_" + type);
  document.getElementById("viewAsMenu_" + type).setAttribute("checked", 'true');

  /*
  var menuIcons = document.getElementById('viewAsIconsMenu');
  var menuList = document.getElementById('viewAsListMenu');
  if( aType == 'icons' ){
    list.parentNode.selectedItem = document.getElementById("viewAsIconsSelectItem");
    menuIcons.setAttribute('checked', 'true');
  }
  else{
    list.parentNode.selectedItem = document.getElementById("viewAsIconsSelectItem"); ;
    menuList.setAttribute('checked', 'true');
  }
  */

  var prefService = Components.classes["@mozilla.org/preferences-service;1"]
        .getService(Components.interfaces.nsIPrefBranch);
  var root = prefService.getBranch("extensions.outwit.");
  root.setCharPref('oWDocs.mode', type);
  gContainer.mode = type;
};


function sortBy( aType ){
  var isInvert    = document.getElementById('menu-sort-invert').getAttribute('checked');
  var direction  = isInvert ? SortService.kAscending : SortService.kDescending;

  switch(aType){
    case 'invert':
      gContainer.sort( SortService.defaultSort, direction );
    break;

    case 'order':
      gContainer.sort(SortService.kOrder, SortService.kNormal );
    break;

    case 'name':
      gContainer.sort(SortService.kName, direction );
    break;

    case 'size':
      gContainer.sort(SortService.kSize, direction );
    break;

    case 'date':
      gContainer.sort(SortService.kDate, direction );
    break;

    case 'type':
      gContainer.sort(SortService.kType, direction );
    break;

    case 'mediaUrl':
      gContainer.sort(SortService.kMediaUrl, direction );
    break;

    case 'sourceUrl':
      gContainer.sort(SortService.kSourceUrl, direction );
    break;
  }
};

function BrowserDownloadsUI(){
  Components.classes["@mozilla.org/download-manager-ui;1"]
            .getService(Components.interfaces.nsIDownloadManagerUI).show(window);
};



outwitDocs.extractControls = {};

outwitDocs.extractControls.locationChangeListener = function(event){
  widgets.page.extractorManager.getInstanceForLocation("documents", event.URI.spec)
    .addProgressListener(outwitDocs.extractControls.getListener(gCategory));
};

outwitDocs.extractControls.getListener = function(aCategory) {
  return {
    onStart: function() {
    },
    onStop: function() {
    },
    onAbort: function() {
    },
    onProgress: function(aDocumentBean) {
      outwitDocs.extractControls.newDocument(aDocumentBean, aCategory);
    }
  };
};


outwitDocs.extractControls.newDocument = function(aDocumentBean, aCategory) {
  try {
  var documentBean = outwitKit.URLHistoryService.getBean(aDocumentBean, null, true);

  var typeDesc;
  try {
    typeDesc = coreKit.localeService.getString(aDocumentBean.URI.fileExtension.toLowerCase(), 'chrome://outwit-modules-docs/locale/mimetypes.properties');
  }
  catch(e) {
    typeDesc = coreKit.localeService.getString('undefined', 'chrome://outwit-modules-docs/locale/mimetypes.properties');
  }

  var aBean = {
    src:"moz-icon://." + aDocumentBean.URI.fileExtension.toLowerCase() + "?size=32",
    docSize: aDocumentBean.weight,
    fileType: typeDesc,
    lastModified: aDocumentBean.lastModified,
    mediaUrl: aDocumentBean.URI.spec,
    sourceUrl: aDocumentBean.sourceURI,
    filename: aDocumentBean.URI.fileName,
    emblems:{
      kCatch:'chrome://outwit-modules-docs/skin/valid.png',
      kDownloading:'chrome://outwit-kernel/skin/searching_16.png',
      kDownload:'chrome://outwit-modules-docs/skin/download.png',
      _emblems:[],
      add:function( anEmblem ){
        
        var index = this._emblems.indexOf( anEmblem );
        if( index != -1 ) return;
        this._emblems.push(anEmblem);
      },
      remove:function( anEmblem ){
        var index = this._emblems.indexOf( anEmblem );
        if( index != -1 ){
          this._emblems.slice(index, 1);
        }
      }
    }
  };

  try {
    aBean.filename = decodeURI(aBean.filename);
  }
  catch(e) {
    aBean.filename = unescape(aBean.filename);
  }

  //try to catch it
  if (optionsCtrl.autoCatch && autocatchRule.testRule(aBean)) {
    coreKit.coreMessager.observe('CATCH', 1, 1, '', aBean);
  }

  //var category = CategoryManager.getCategory(aCategoryName);
  var category = aCategory;
  if (!category) return;

  var engine = category.getEngine();
  if (engine) {
    outwitDocs.gEngineManager.resetNoResult(engine);
  }
//  if( gCategory == null ){
//    return;
//      gCategory       = CategoryManager.add(mainKit.originalURI);
//      tree.current    = mainKit.originalURI;
//    }
  var beanAdded = category.add(aBean);
  if( searchTreeCtrl.isInCatch( aBean.mediaUrl ) )
    category.mark( aBean.mediaUrl );
  searchTreeCtrl.synchronize();

  gContainer.appendItem(aBean);
/*    if(searchTreeCtrl.isCurrent(category.getName()) && beanAdded){
    var index = gContainer.appendItem(aBean);
    if( !Comparator.isDefault
        && (Comparator.func( aBean.filename )
            && Comparator.checkType( aBean.filename ))){
      gContainer.select([index]);
    }
  }
  */
  }
  catch(e) {
    ow.log.error("Error appending document", e);
  }
};
