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

/**
 * searchTreeCtrl is an object to manage the GUI search tree.
 *
 */
var searchTreeCtrl = {
  /**
   * Internal xul tree object
   */
  _tree:null,

  /**
   * Getter for XUL tree
   */
  get tree(){
    if( !this._tree)
      this._tree = document.getElementById('searchTree');
    return this._tree;
  },

  /**
   * Getter for XUL treechildren
   */
  get treechildren() {
    return this.tree.lastChild;
  },

  /**
   * Currently selected categories
   */
  current:[],

  /**
   * Check if a category is selected
   */
  isCurrent: function(aCategory) { return this.current.indexOf(aCategory) != -1; },

  //firstSearchHack: true,
  //firstSearchCat: null
};


/**
 * Handles a keypress event
 */
searchTreeCtrl.handleKey = function(anEvent) {
  // XXX WHY is it VK_BACK in XBL handlers and VK_BACK_SPACE in JS ??
  if (anEvent.keyCode == KeyEvent.DOM_VK_DELETE
      || anEvent.keyCode == KeyEvent.DOM_VK_BACK_SPACE) {
    searchTreeCtrl.removeSelection();
    return;
  }

  switch (anEvent.charCode) {
    case 65:
    case 97:
      if (anEvent.ctrlKey || anEvent.metaKey) {
        this.tree.view.selection.selectAll();
      }
      break;
  }
};


searchTreeCtrl.startThrobber = function() {
  var childs = this.treechildren.childNodes;
  for( var i = 0 ; i < childs.length ; i++ ){
    var startIt = childs[i].getAttribute("properties") == gCategory.getName();
    var cell = childs[i].firstChild.firstChild;
    var props = cell.getAttribute("properties");
    if (startIt) {
      if (props.indexOf('browsing') == -1) {
        cell.setAttribute('properties', props + ' browsing');
      }
    }
    else { 
      if (props.indexOf('browsing') != -1) {
        cell.setAttribute('properties', props.replace('browsing', '').replace(/ +/g, ''));
      }
    }
  }

};

searchTreeCtrl.stopThrobber = function() {
  var childs = this.treechildren.childNodes;
  for( var i = 0 ; i < childs.length ; i++ ){
    var cell = childs[i].firstChild.firstChild;
    var props = cell.getAttribute("properties");
    if (props.indexOf('browsing') != -1) {
      cell.setAttribute('properties', props.replace('browsing', '').replace(/ +/g, ''));
    }
  }

};


/**
 * Synchronize all categories with the search tree
 *
 * XXX optim no need to resync all everytime we get a doc !
 */
searchTreeCtrl.synchronize = function(){
  var tChildren = this.treechildren;
  var cat  = CategoryManager.getAll();

  var currentCat = gCategory;

  for( var i = 0 ; i < cat.length ; i++ ){
    var isFound = false;
    let catName     = cat[i].getName();
    let theNumber  =  cat[i].length();

    if(catName == 'catch') continue;

    var childs = tChildren.childNodes;
    for( var j = 0 ; j < childs.length ; j++ ){
      if(childs[j].getAttribute("properties") == catName){
        isFound = childs[j];
        break;
      }
    }

    if(isFound){
      var tCell = isFound.firstChild.lastChild;
      tCell.setAttribute("label", cat[i].getViewName() + ' (' + theNumber + ')');
    }
    else {
//      if (this.firstSearchHack) {
//        this.firstSearchCat = catName;
//        this.firstSearchHack = false;
//      }
//      if (this.firstSearchCat == catName && theNumber == 0) return;
      if (theNumber != 0) {
      var tItem   = document.createElement('treeitem');
      var tRow    = document.createElement('treerow');
      var tCell   = document.createElement('treecell');
      var tCell2  = document.createElement('treecell');
      tItem.appendChild( tRow );
      tRow.appendChild( tCell );
      tRow.appendChild( tCell2 );

      tItem.setAttribute("properties", catName);

      var properties = (catName.substr(0, 4) == 'file' ? 'directory' : 'virtual');
      if (gCategory.getName() == catName) {
        properties += " browsing";
      }

      tCell.setAttribute("properties", properties);

      tCell2.setAttribute("label", cat[i].getViewName() + ' (' + theNumber + ')');
      tChildren.appendChild( tItem );
      this.select(catName);
      }
    }
  }
};


/**
 * Gets the current selected treeitems
 */
searchTreeCtrl.getSelection = function() {
  var start = new Object();
  var end = new Object();
  var numRanges = this.tree.view.selection.getRangeCount();

  var selected = [];

  for (var t = 0; t < numRanges; t++){
    this.tree.view.selection.getRangeAt(t,start,end);
    for (var v = start.value; v <= end.value; v++){
      selected.push(this.tree.view.getItemAtIndex(v));
    }
  }
  return selected;
};


/**
 * Displays the content of the selected categories
 * in the view
 */
searchTreeCtrl.display = function(){
  gNotification.hideTopNotificationNoResult();
  var selected = this.getSelection();
  if (!selected.length) return;

  gContainer.clear();
  this.current = [];
  for (var i = 0; i < selected.length; ++i) {
    var nameEl = selected[i];
    var name = nameEl.getAttribute('properties');
    var cat = CategoryManager.getCategory( name );
    this.current.push(name);

    var data = cat.getAll();
    for (let i in data) {
      var aBean = data[i];
      gContainer.appendItem(aBean);
    }
  }
};


/**
 * Force a selection in the tree, like if user clicks on it
 */
searchTreeCtrl.select = function( aCategory ){
  this.current = [aCategory];
  if( aCategory == 'catch'){
    this.tree.view.selection.clearSelection();
    return;
  }
  var childs = this.treechildren.childNodes;
  for( var i = 0 ; i < childs.length ; i++ ){
    if(childs[i].getAttribute("properties") == aCategory){
      this.tree.view.selection.select(i);
      return;
    }
  }
};


/**
 * XXX unused ?
 * */
searchTreeCtrl.showCatch = function(){
  this.select( 'catch' );
  gContainer.clear();
  if( CategoryManager.getCategory('catch') == undefined )
    return;
  var data = CategoryManager.getCategory('catch').getAll();
  for( let i in data){
    var aBean = data[i];
    gContainer.appendItem(aBean);
  }
};


/**
 * XXX unused ?
 */
searchTreeCtrl.isInCatch = function( anImage ){
  var isInCatch = false;
  if( CategoryManager.getCategory('catch') == undefined )
    return false;
  var data = CategoryManager.getCategory('catch').getAll();
  for( let i in data){
    if( anImage == data[i].mediaUrl ){
      isInCatch = true;
      break;
    }
  }

  return isInCatch;
};


/**
 * Removes a treeitem from the tree
 */
searchTreeCtrl.removeByItem = function(anItem) {
  var name = anItem.getAttribute('properties');
  if (gCategory == CategoryManager.getCategory(name)) {
    gCategory = null;
    historyHandler.stop(true);
  }
  if (this.isCurrent(name)) {
    gContainer.clear();
    // XXX select better (as in catch)
    this.tree.view.selection.select(0);
  }
  CategoryManager.remove(name);
  this.treechildren.removeChild(anItem);
  
  if (!this.treechildren.childNodes.length) {
    gContainer.clear();
  }
};


/**
 * Removes current selection
 */
searchTreeCtrl.removeSelection = function() {
  var selected = this.getSelection();
  for (var i = 0; i < selected.length; ++i) {
    this.removeByItem(selected[i]);
  }
};


/**
 * Removes empty searches
 */
searchTreeCtrl.removeEmpty = function() {
  var childs = this.treechildren.childNodes;
  var toRemove = [];
  for (var i = 0; i < childs.length; ++i) {
    var item = childs[i];
    var cellName = item.firstChild.lastChild;
    if (/\(0\)$/.test(cellName.getAttribute("label")))
      toRemove.push(item);
  }

  for (var i = 0; i < toRemove.length; ++i)
    this.removeByItem(toRemove[i]);
};


/**
 * Removes all searches
 */
searchTreeCtrl.removeAll = function() {
  var tChildren = this.treechildren;
  while (tChildren.hasChildNodes())
    this.removeByItem(tChildren.firstChild);
};


searchTreeCtrl.openURL = function() {
  for (var cur = 0; cur < this.current.length; ++cur) {
    menuCtrl.browser.open(CategoryManager.getCategory(this.current[cur]).getLastUrl());
  }
};

searchTreeCtrl.copyURL = function() {
  var str = "";
  for (var i = 0; i < this.current.length; ++i) {
    str += CategoryManager.getCategory(this.current[i]).getLastUrl();
    if (i != this.current.length - 1) str += "\r\n";
  }
  var clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
                                 .getService(Components.interfaces.nsIClipboardHelper);
  clipboardHelper.copyString(str);
};
