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

/**
 * @name optionsCtrl
 * @static
 * Simple class to manage options
 * and change done by the user to the application.
 */
 
var optionsCtrl = {
  _lockRefresh:false,
  get lockRefresh(){
    return this._lockRefresh;
  },
  set lockRefresh(aValue){
    //Avoid doing multiple time refresh
    this._lockRefresh = aValue;
    if(this._lockRefresh){
      coreKit.timerService.cancelTimer(this._timeoutRefresh);
      this._timeoutRefresh = coreKit.timerService.setTimer(200, null, function() {
        optionsCtrl.ui.refresh();
        optionsCtrl._lockRefresh = false;
      });
    }
  },
  _autoCatch:false,
  _autoBrowse:false,
  _autoSave:false,
  _fullScreen:false,
  _options:false,
  get options(){
    return this._options;
  },
  set options( aValue ){
    this._options = aValue;
  },

  get autoCatch(){
    return this._autoCatch;
  },
  set autoCatch(aValue){
    //document.getElementById("menuAutocatch").setAttribute('checked', aValue);
    this._autoCatch = aValue;
  },
  get autoBrowse(){
    return this._autoBrowse;
  },
  set autoBrowse(aValue) {
    this._autoBrowse = aValue;
  },
  get autoSave(){
    return this._autoSave;
  },
  set autoSave(aValue){
    ow.app.kernel.prefs.setBool('oWDocs.autosave', aValue);
    document.getElementById("menuAutosave").setAttribute('checked',aValue);
    document.getElementById("optionsAutoSave").setAttribute('checked',aValue);
    this._autoSave = aValue;
  },
  get fullScreen(){
    return window.fullScreen;
  },
  set fullScreen(aValue){
    document.getElementById("menuFullscreen").setAttribute('checked',aValue);
    window.fullScreen = aValue;
    this._fullScreen = aValue;
  },

  get autoSaveFolder() {
    return ow.app.kernel.prefs.getString('oWDocs.autosave.folder', "");
  },
  set autoSaveFolder(aValue) {
    ow.app.kernel.prefs.setString('oWDocs.autosave.folder', aValue);
  },

  chooseSaveFolder: function(setAutoSave) {
    var fm = coreKit.fileManager;
    var fileToSave = fm.filePicker.get('Save documents in...');
    if (fileToSave) {
      optionsCtrl.autoSaveFolder = fileToSave.path;
    }
    if (setAutoSave) optionsCtrl.autoSave = (fileToSave ? true : false);
    return optionsCtrl.autoSaveFolder;
  },

  autoSaveSwitch: function(forceChoose) {
    try {
    if (!optionsCtrl.autoSave) {
      if (forceChoose || !optionsCtrl.autoSaveFolder) {
        optionsCtrl.chooseSaveFolder(true);
      }
      else {
        optionsCtrl.autoSave = true;
      }
    }
    else {
      optionsCtrl.autoSave = false;
    }
    return optionsCtrl.autoSave;
    }catch(e) { dump(e + "\n"); }
  },

  changePattern: function( aPattern ){
    ow.app.kernel.prefs.setString("oWDocs.autocatch.urlpattern", aPattern);
    Comparator.apply();
  },

  
  /* fileTypes: {
    'pdf':['pdf'],
    'documents':['doc','docx','odt','txt','sxw','rtf', 'txt'],
    'datasheets':['xls', 'xlsx', 'csv','ods'],
    'presentations':['ppt', 'pps','pptx', 'ppsx','swf','key']
  }, */
  
  fileTypes: {
    'pdf': [],
    'documents':[],
    'datasheets':[],
    'presentations':[]
  },

  fileFormatChange: function( anItem ){
    var id = anItem.getAttribute("id");
    var checked = (anItem.getAttribute("checked") == "true");
    if (id == "fileFormat_any") {
      if (checked) {
        for (var i in this.fileTypes) {
          var el = document.getElementById("fileFormat_" + i);
          el.setAttribute("checked", "true");
        }
      } 
    }
    else {
      if (checked) {
        var allChecked = true;
        for (var i in this.fileTypes) {
          var el = document.getElementById( "fileFormat_" + i );
          if (el.getAttribute("checked") != "true") {
            allChecked = false;
            break;
          }
        }
        if (allChecked) {
          var el = document.getElementById( "fileFormat_any");
          el.setAttribute("checked", "true");
        }
      }
      else {
        var el = document.getElementById( "fileFormat_any");
        el.setAttribute("checked", "false");
      }
    }

    this.fileFormatSync('interface');
  },
  
  queryTypeChanged: function( anItem ){
    var root = this._prefService.getBranch("extensions.outwit.");
    var pref = anItem.getAttribute('preference');

    root.setCharPref(pref, anItem.selectedItem.value);
  },

  fileFormatSync: function( aFrom ){
    if( aFrom == 'interface' ){
      for (var i in this.fileTypes) {
        var el = document.getElementById("fileFormat_" + i);
        var pref = el.getAttribute('preference');
        var root = this._prefService.getBranch("extensions.outwit.");
        root.setBoolPref(pref,el.checked);
      }
      var elAny =  document.getElementById("fileFormat_any");
      var pref = elAny.getAttribute('preference');
      var root = this._prefService.getBranch("extensions.outwit.");
      root.setBoolPref(pref,elAny.checked);
    }
    else{
      for (var i in this.fileTypes) {
        var root = this._prefService.getBranch("extensions.outwit.");
        var pref  = root.getBoolPref('oWDocs.autocatch.' + i);
        var el    = document.getElementById('fileFormat_' + i);
        if(pref)
          el.setAttribute('checked','true');
        else
          el.setAttribute('checked','false');
      }
    }
    Comparator.apply();
  }
};




/**
 * @name optionsCtrl._optionsPrefs
 * @private
 * An associative array storing prefs and their default
 * value.
 * Use for internal usage only.
 */
optionsCtrl._optionsPrefs = [];


/**
 * @name optionsCtrl._prefService
 * @private
 * Reference to the pref service
 */
optionsCtrl._prefService = null;


optionsCtrl.initFileTypes = function() {
  var wordNetExts = outwitKit.wordNet.getDocumentExtensions();

  var exprTypes = {
    pdf: /fileextension\.binaryfile\.layout/i,
    presentations: /fileextension\..+\.presentation/i,
    datasheets: /fileextension\.(?:.+\.datasheet|textfile\.data)/i,
    documents: /fileextension\..+\.(?:richtext|simpletext)/i
  };

  for (var i in wordNetExts) {
    var extClass = wordNetExts[i]["class"];
    for (var expr in exprTypes) {
      if (exprTypes[expr].test(extClass)) {
        optionsCtrl.fileTypes[expr].push(wordNetExts[i].extension);
      }
    }
  }

};


/**
 * @name optionsCtrl.init
 * @static
 * Initialize the options from the user prefs
 */
optionsCtrl.init = function(){
    //var urlPattern = ow.app.kernel.prefs.getString("oWDocs.autocatch.urlpattern","");
    //document.getElementById('urlpattern').setAttribute( 'value', urlPattern );
  this._prefService = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefService);
  this._prefService.QueryInterface(Components.interfaces.nsIPrefBranch);


  this._optionsPrefs.push(["oWDocs.autocatch.urlpattern", this._prefService.PREF_STRING, ""]);
  this._optionsPrefs.push(["oWDocs.zoom", this._prefService.PREF_STRING, "1"]);
  this._optionsPrefs.push(["oWDocs.mode", this._prefService.PREF_STRING, "icons"]);
  this._optionsPrefs.push(["oWDocs.autocatch.any", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWDocs.autocatch.pdf", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWDocs.autocatch.documents", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWDocs.autocatch.datasheets", this._prefService.PREF_BOOL, true]);
  //this._optionsPrefs.push(["oWDocs.autocatch.text", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWDocs.autocatch.presentations", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWDocs.queryTypesInQuery", this._prefService.PREF_STRING, true]);

  //this._optionsPrefs.push(["oWDocs.autosave.folder", this._prefService.PREF_STRING, ""]);

  var root = this._prefService.getBranch("extensions.outwit.");
  // Instantiate all prefs in case the don't prexist
  for(var i = 0 ; i < this._optionsPrefs.length ; i++){
    var pref = this._optionsPrefs[i];
    var prefState = root.getPrefType(pref[0]);
    //http://developer.mozilla.org/En/NsIPrefBranch
    if(prefState == 0){ //PREF_INVALID
      switch(pref[1]){
        case this._prefService.PREF_STRING:// PREF_STRING
          root.setCharPref(pref[0], pref[2]);
        break;
        case this._prefService.PREF_INT:// PREF_INT
          root.setIntPref(pref[0], pref[2]);
        break;
        case this._prefService.PREF_BOOL:// PREF_BOOL
          root.setBoolPref(pref[0], pref[2]);
        break;
      }
    }
  }

  // Oki. Now, we're sure to have the pref just use some observer
  this._prefService.QueryInterface(Components.interfaces.nsIPrefBranch2);
  this._prefService.addObserver("", this, false);


  // configure the main features
  // Do this at end for the first run, otherwise a lot if stuff
  // are not already registered in the user prefs!
  this.autoBrowse = false;
  this.autoCatch = false;
  //this.autoSave = false;

  //this.options = this.ui.checkDefault();
  //this.fileFormatSync();

  try{
    var prefService = Components.classes["@mozilla.org/preferences-service;1"]
      .getService(Components.interfaces.nsIPrefBranch);
    var root = prefService.getBranch("extensions.outwit.");
    ZoomManager.zoom = parseFloat(root.getCharPref("oWDocs.zoom","1"));
    var mode = root.getCharPref("oWDocs.mode","icons");
    viewAs(mode);
  }
  catch(e){
  }

  // Let the user pref on click behavior on the urlbar
  var prefService = Components.classes["@mozilla.org/preferences-service;1"]
          .getService(Components.interfaces.nsIPrefBranch);

  outwitDocs.UIControls.URLBar.setAttribute("clickSelectsAll", prefService.getBoolPref("browser.urlbar.clickSelectsAll",false));
  
  this.initFileTypes();

  switch (prefService.getCharPref("extensions.outwit.oWDocs.queryTypesInQuery")) {
    case "selectionPanel":
      document.getElementById("fileFormatDeck").selectedIndex = 1;
      document.getElementById("queriesToPerform").selectedIndex = 1;
      break;
    case "all":
    default:
      document.getElementById("fileFormatDeck").selectedIndex = 0;
      document.getElementById("queriesToPerform").selectedIndex = 0;
      break;
  }

  if (prefService.getBoolPref("extensions.outwit.oWDocs.autosave.remember", false)
      && prefService.getBoolPref("extensions.outwit.oWDocs.autosave", false)
      && prefService.getCharPref("extensions.outwit.oWDocs.autosave.folder", "")) {
    this.autoSave = prefService.getBoolPref("extensions.outwit.oWDocs.autosave", false);
  }
  else this.autoSave = false;
};

optionsCtrl.unload = function() {
  this._prefService.removeObserver("", this, false);
};

/**
 * @name optionsCtrl.observe
 * @static
 * Look if something has change in the user pref
 * and apply the change to the interface if needed
 */
optionsCtrl.observe = function(subject, topic, data){
  if(topic != "nsPref:changed") return;

  switch(data){
    case "extensions.outwit.oWDocs.queryTypesInQuery":
      if (optionsCtrl) {
        switch (optionsCtrl._prefService.getCharPref(data)) {
          case "selectionPanel":
            document.getElementById("fileFormatDeck").selectedIndex = 1;
	      document.getElementById("queriesToPerform").selectedIndex = 1;
            break;
          case "all":
          default:
            document.getElementById("fileFormatDeck").selectedIndex = 0;
	      document.getElementById("queriesToPerform").selectedIndex = 0;
            break;
        }
      }
    break;
  }
};


/**
 * @name optionsCtrl.reset
 * @static
 * Reset the user pref to her default state and 
 * with/without applying the change
 * @param {boolean} applyChange - Apply the change
 */
optionsCtrl.reset = function( applyChange ){
  this._isFrozen = !applyChange;
  var root = this._prefService.getBranch("extensions.outwit.");
  // Instantiate all prefs in case the don't prexist
  for(var i = 0 ; i < this._optionsPrefs.length ; i++){
    var pref = this._optionsPrefs[i];
    switch(pref[1]){
      case this._prefService.PREF_STRING:// PREF_STRING
        root.setCharPref(pref[0], pref[2]);
      break;
      case this._prefService.PREF_INT:// PREF_INT
        root.setIntPref(pref[0], pref[2]);
      break;
      case this._prefService.PREF_BOOL:// PREF_BOOL
        root.setBoolPref(pref[0], pref[2]);
      break;
    }
  }
  this._isFrozen = false;
};


/**
 * @name optionsCtrl.ui
 * @static
 * Object connected to the ui to who contains
 * function to change the ui
 */
optionsCtrl.ui = {};

/**
 * @name optionsCtrl.ui.checkDefault
 * @static
 * Check some selected pref for their default value
 *
 * @return {boolean}  true if all pref are default
 *                    false otherwise
 */
optionsCtrl.ui.checkDefault = function( ){
  //Check default if we have to activate the options stuff or not
  try{
    var prefsToCheck = [];
    prefsToCheck.push(["oWDocs.autocatch.urlpattern", optionsCtrl._prefService.PREF_STRING, ""]);
    prefsToCheck.push(["oWDocs.autocatch.any", optionsCtrl._prefService.PREF_BOOL, true]);
    prefsToCheck.push(["oWDocs.autocatch.pdf", optionsCtrl._prefService.PREF_BOOL, true]);
    prefsToCheck.push(["oWDocs.autocatch.documents", optionsCtrl._prefService.PREF_BOOL, true]);
    prefsToCheck.push(["oWDocs.autocatch.datasheets", optionsCtrl._prefService.PREF_BOOL, true]);
    prefsToCheck.push(["oWDocs.autocatch.presentations", optionsCtrl._prefService.PREF_BOOL, true]);
    //prefsToCheck.push(["oWDocs.autocatch.text", optionsCtrl._prefService.PREF_BOOL, true]);
    var root = optionsCtrl._prefService.getBranch("extensions.outwit.");
    var isDefault = true;

    for(var i = 0 ; i < prefsToCheck.length ; i++){
      var pref = prefsToCheck[i];
      switch(pref[1]){
        case optionsCtrl._prefService.PREF_STRING:// PREF_STRING
          if(root.getCharPref(pref[0]) != pref[2])
            isDefault = false;
        break;
        case optionsCtrl._prefService.PREF_INT:// PREF_INT
          if(root.getIntPref(pref[0]) != pref[2])
            isDefault = false;
        break;
        case optionsCtrl._prefService.PREF_BOOL:// PREF_BOOL
          if(root.getBoolPref(pref[0]) != pref[2])
            isDefault = false;
        break;
      }
    }
    return !isDefault;
  }
  catch(e){
  }
  return false;

};
