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

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

  get autoCatch(){
    return this._autoCatch;
  },
  set autoCatch(aValue){
    document.getElementById("owCatchButton").setAttribute("active", aValue);
    document.getElementById("owImagesContainer").optionsMode.autoCatch.checked = aValue;
    document.getElementById("menuAutocatch").setAttribute('checked', aValue);
    this._autoCatch = aValue;
  },
  get autoBrowse(){
    return this._autoBrowse;
  },
  set autoBrowse(aValue){
    document.getElementById("owBrowseButton").setAttribute("active", aValue);
    document.getElementById("owImagesContainer").optionsMode.autoBrowse.checked = aValue;
    document.getElementById("menuAutobrowse").setAttribute('checked',aValue);
    this._autoBrowse = aValue;
  },
  get autoSequences(){
    return this._autoSequences;
  },
  set autoSequences(aValue){
    this._autoSequences = aValue;
  },
  get autoSequencesAll(){
    return this._autoSequencesAll;
  },
  set autoSequencesAll(aValue){
    this._autoSequencesAll = aValue;
  },
  get autoSave(){
    return this._autoSave;
  },
  set autoSave(aValue){
    try{
      if(this._autosaveString == null)
        this._autosaveString = coreKit.localeService.getString('autosaveIsDisabled', 'chrome://outwit-modules-images/locale/optionsCtrl.properties');
    }catch(e){
    }
    document.getElementById("owAutoSaveButton").setAttribute("active", aValue);
    document.getElementById("owImagesBoxInfoAutoSave").setAttribute("checked", aValue);
    document.getElementById("menuAutosave").setAttribute('checked',aValue);
    optionsCtrl.refreshInfoBoxPath();
    if (aValue) {
      document.getElementById("owImagesBoxInfoNoPath").setAttribute("hidden", "true");
    }
    else {
      document.getElementById("owImagesBoxInfoNoPath").removeAttribute("hidden");
    }
    this._autoSave = aValue;
  },
  refreshInfoBoxPath : function() {
    var infoBoxPath = ow.app.kernel.prefs.getString("oWImages.autocatch.autosave.folder", "");
    if (optionsCtrl.autoRename && infoBoxPath) {
      var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
      file.initWithPath(infoBoxPath);
      file.append(optionsCtrl.autoRenamePattern);
      infoBoxPath = file.path;
    }
    document.getElementById("owImagesBoxInfoSavePath").setAttribute("value", infoBoxPath); 
  },
  get autoRename() {
   return this._autoRename;
  },
  set autoRename(value) {
    document.getElementById("owImagesContainer").optionsMode.autoRename.checked = value;
//    document.getElementById("owImagesContainer").optionsMode.autoRenamePattern.disabled = !value;
    this._autoRename = value;
    optionsCtrl.refreshInfoBoxPath();
  },
  get autoRenamePattern() {
   return ow.app.kernel.prefs.getString('oWImages.autorename.pattern', '');
  },
  get fullScreen(){
    return window.fullScreen;
  },
  set fullScreen(aValue){
    document.getElementById("menuFullscreen").setAttribute('checked',aValue);
    window.fullScreen = aValue;
    this._fullScreen = aValue;
  },

  chooseSaveFolder: function(setAutoSave) {
    return document.getElementById("owImagesContainer").optionsMode.chooseSaveFolder(setAutoSave);
  },

  checkSaveFolder: function(p_checkPrefToo) {
    var checkPrefToo = (typeof(p_checkPrefToo) == 'undefined' ? true : p_checkPrefToo);
    var optionsMode = document.getElementById("owImagesContainer").optionsMode;
    return (optionsMode.autoSaveFolder.value
            ? optionsMode.autoSaveFolder.value
            : (checkPrefToo
               ? ow.app.kernel.prefs.getString('oWImages.autocatch.autosave.folder', '')
               : false));
  },

  autoSaveSwitch: function(p_checkPrefToo) {
    var checkPrefToo = (typeof(p_checkPrefToo) == 'undefined' ? true : p_checkPrefToo);
    var optionsMode = document.getElementById("owImagesContainer").optionsMode;
    if (!optionsCtrl.autoSave) {
      //if (!optionsCtrl.autoCatch && !window.confirm(coreKit.localeService.getString('autosaveImpliesCatch', 'chrome://outwit-modules-images/locale/optionsCtrl.properties')))
      //  return;
      if (!optionsCtrl.checkSaveFolder(checkPrefToo))
        optionsCtrl.autoSave = (optionsMode.chooseSaveFolder(true) ? true : false);
      else
        optionsCtrl.autoSave = true;
      //if (!optionsCtrl.autoCatch && optionsCtrl.autoSave)
      //  optionsCtrl.autoCatch = true;
    }
    else {
      optionsCtrl.autoSave = false;
    }
    return false;
  },

  autoBrowseSwitch: function() {
    optionsCtrl.autoBrowse = !optionsCtrl.autoBrowse;
    if (optionsCtrl.autoBrowse) {
      outwitImages.browserControls.runAutoBrowse();
    }
    else {
      outwitImages.browserControls.stopBrowse();
    }
  },

  autoSequencesSwitch: function(all) {
    optionsCtrl.autoSequences = !optionsCtrl.autoSequences;
    if (all) {
      optionsCtrl.autoSequencesAll = !optionsCtrl.autoSequencesAll;
    }
  }
};




/**
 * @name optionsCtrl._optionsPrefs
 * @private
 * An associative array storing prefs and their default
 * value. And a "dontReset", in [3].
 * Use for internal usage only.
 */
optionsCtrl._optionsPrefs = [];


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


/**
 * @name optionsCtrl.init
 * @static
 * Initialize the options from the user prefs
 */
optionsCtrl.init = function(){
  try{
    ImageColor.initialize();
      /*document.getElementById("owImagesTopPanel").removeAttribute("style"); //seems strange but this is a linux bug.
      document.getElementById("owImagesContainer").removeAttribute("collapsed");
      document.getElementById("owImagesBottomPanel").removeAttribute("collapsed");
      if(!this._isinit){
        document.getElementById("owImagesContainer").thumbnails.load();
        this._isinit = true;
      }*/
  }catch(e){
    ow.log.error("Error initializing colors", e);
  }
  try{
    this.ui._gallery = document.getElementById("owImagesContainer").thumbs;
  }catch(e){}
  


  this._prefService = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefService);
  this._prefService.QueryInterface(Components.interfaces.nsIPrefBranch);


  this._optionsPrefs.push(["oWImages.autocatch.cond1.condition", this._prefService.PREF_INT, 0]);
  this._optionsPrefs.push(["oWImages.autocatch.cond1.comparator", this._prefService.PREF_INT, 0]);
  this._optionsPrefs.push(["oWImages.autocatch.cond1.size", this._prefService.PREF_INT, -1]);
  this._optionsPrefs.push(["oWImages.autocatch.cond2.condition", this._prefService.PREF_INT, 0]);
  this._optionsPrefs.push(["oWImages.autocatch.cond2.comparator", this._prefService.PREF_INT, 0]);
  this._optionsPrefs.push(["oWImages.autocatch.cond2.size", this._prefService.PREF_INT, -1]);
  this._optionsPrefs.push(["oWImages.autocatch.urlpattern", this._prefService.PREF_STRING, ""]);
  this._optionsPrefs.push(["oWImages.autocatch.any", this._prefService.PREF_BOOL, true]);
  // XXXXX add heic,heif ?
  this._optionsPrefs.push(["oWImages.autocatch.png", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWImages.autocatch.gif", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWImages.autocatch.jpg", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWImages.autocatch.format.portrait", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWImages.autocatch.format.landscape", this._prefService.PREF_BOOL, true]);

  this._optionsPrefs.push(["oWImages.autocatch.autosave.folder", this._prefService.PREF_STRING, ""]);
  this._optionsPrefs.push(["oWImages.autocatch.autosave.remember", this._prefService.PREF_BOOL, false]);
  this._optionsPrefs.push(["oWImages.autorename.pattern", this._prefService.PREF_STRING, coreKit.localeService.getString('defaultRenamePattern', 'chrome://outwit-modules-images/locale/main.properties')]);
  this._optionsPrefs.push(["download.concurrent", this._prefService.PREF_INT, 5]);

  this._optionsPrefs.push(["oWImages.autobrowse", this._prefService.PREF_BOOL, true]);
  this._optionsPrefs.push(["oWImages.hue", this._prefService.PREF_INT, 50]);
  this._optionsPrefs.push(["oWImages.transparency", this._prefService.PREF_INT, 150]);
  this._optionsPrefs.push(["oWImages.allowBrowserJavascript", this._prefService.PREF_BOOL, true]);

  this._optionsPrefs.push(["oWImages.thumbnails.limit", this._prefService.PREF_INT, 1500]);
  this._optionsPrefs.push(["thumbnails.lines", this._prefService.PREF_INT, 4]);
  this._optionsPrefs.push(["thumbnails.inertia", this._prefService.PREF_INT, 3]);
  this._optionsPrefs.push(["thumbnails.margin", this._prefService.PREF_BOOL, false]);
  this._optionsPrefs.push(["thumbnails.minHeight", this._prefService.PREF_INT, 20]);
  this._optionsPrefs.push(["thumbnails.minWidth", this._prefService.PREF_INT, 20]);

  this._optionsPrefs.push(["slideshow.enlarge", this._prefService.PREF_INT, 2]);
  this._optionsPrefs.push(["slideshow.timeout", this._prefService.PREF_INT, 4]);
  this._optionsPrefs.push(["slideshow.minHeight", this._prefService.PREF_INT, 200]);
  this._optionsPrefs.push(["slideshow.minWidth", this._prefService.PREF_INT, 200]);

  this._optionsPrefs.push(["oWImages.dialog.createDir.dontAsk", this._prefService.PREF_BOOL, false, true]);
  this._optionsPrefs.push(["oWImages.dialog.quit.dontAsk", this._prefService.PREF_BOOL, false, true]);
  this._optionsPrefs.push(["oWImages.dialog.emptyCatch.dontAsk", this._prefService.PREF_BOOL, false, true]);


  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 = true;
  this.autoCatch = false;
  //this.autoSave = false;
  this.options = this.ui.checkDefault();


  // try because autosave sets UI checkbox not already painted
  try {
  if (root.getBoolPref('oWImages.autocatch.autosave.remember', false)
      && root.getBoolPref('oWImages.autocatch.autosave', false)
      && root.getCharPref('oWImages.autocatch.autosave.folder', '')) {
    this.autoSave = true;
  }
  else this.autoSave = false;
  }
  catch(e) {
  }
  //Now, jestnuse a setter on global pref to change all stuff accordingly
  //XXX Have to do this

};


/**
 * @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.thumbnails.minHeight":
    case "extensions.outwit.thumbnails.minWidth":
      this.lockRefresh = true;
      break;
    case "extensions.outwit.thumbnails.inertia":
      document.getElementById("owImagesContainer").screenManager.maxTime = this._prefService.getIntPref(data,3)*1000;
      break;
    case "extensions.outwit.thumbnails.lines":
      this.ui.changeLine(this._prefService.getIntPref(data,4));
      break;
    case "extensions.outwit.thumbnails.margin":
    this.ui.changeMargin(this._prefService.getBoolPref(data, false));
      break;
    case "extensions.outwit.oWImages.transparency":
    case "extensions.outwit.oWImages.hue":
      //XXX sorry for that we do it twice if the user change both of them
      this.ui.changeHue(this._prefService.getIntPref("extensions.outwit.oWImages.hue", 50), this._prefService.getIntPref("extensions.outwit.oWImages.transparency", 50));
    break;
    case "extensions.outwit.oWImages.autocatch.autosave.folder":
      if(optionsCtrl && optionsCtrl.autoSave)
        document.getElementById("owImagesBoxInfoSavePath").setAttribute("value", ow.app.kernel.prefs.getString(data,"Autosave is disabled"));
    break;
    case "extensions.outwit.oWImages.allowBrowserJavascript":
       var browser = document.getElementById("content");
       browser.docShell.allowJavascript = this._prefService.getBoolPref(data, true);
//       browser.setAttribute("collapsed", String(!browser.docShell.allowJavascript));
    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];
    if (!pref[3]) {
      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._gallery
 * @private
 * Reference to the main element which contain
 * the gallery
 */
optionsCtrl.ui._gallery = null;


/**
 * @name optionsCtrl.ui.changeLine
 * @static
 * Change the number of lines displayed by the gallery
 * @param {integer} - linesNumber - Number of lines to displayed
 */
optionsCtrl.ui.changeLine = function( linesNumber ){
  if(!this._gallery)
    this._gallery = document.getElementById("owImagesContainer").thumbs;
  this._gallery.lines = linesNumber;
  optionsCtrl.lockRefresh = true;
};


/**
 * @name optionsCtrl.ui.changeMargin
 * @static
 * Activate/desactivate the lines margin in galllery
 * @param {boolean} linesMargin - Active or not the margin
 */
optionsCtrl.ui.changeMargin = function( linesMargin ){
  if(!this._gallery)
    this._gallery = document.getElementById("owImagesContainer").thumbs;
  this._gallery.margin = linesMargin;
  optionsCtrl.lockRefresh = true;
};


/**
 * @name optionsCtrl.ui.refresh
 * @static
 * Recompute the thumbnails gallery
 */
optionsCtrl.ui.refresh = function(){
  if(!this._gallery)
    this._gallery = document.getElementById("owImagesContainer").thumbs;
  this._gallery.refresh( true );
  this._gallery.recompute();
};


/**
 * @name optionsCtrl.ui.changeHue
 * @static
 * Change the hue of the interface
 * @param {integer} aHue - The new hue to apply
 * @param {integer} aValue - The new value to apply
 */
optionsCtrl.ui.changeHue = function( aHue, aValue ){
  try{
    if(!this._gallery)
      this._gallery = document.getElementById("owImagesContainer").thumbs;
    ImageColor.applySkin( aHue, aValue );
    optionsCtrl.lockRefresh = true;
  }catch(e){
  }
};


/**
 * @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
  var prefsToCheck = [];
  prefsToCheck.push(["oWImages.autocatch.cond1.condition", optionsCtrl._prefService.PREF_INT, 0]);
  prefsToCheck.push(["oWImages.autocatch.cond1.comparator", optionsCtrl._prefService.PREF_INT, 0]);
  prefsToCheck.push(["oWImages.autocatch.cond1.size", optionsCtrl._prefService.PREF_INT, -1]);
  prefsToCheck.push(["oWImages.autocatch.cond2.condition", optionsCtrl._prefService.PREF_INT, 0]);
  prefsToCheck.push(["oWImages.autocatch.cond2.comparator", optionsCtrl._prefService.PREF_INT, 0]);
  prefsToCheck.push(["oWImages.autocatch.cond2.size", optionsCtrl._prefService.PREF_INT, -1]);
  prefsToCheck.push(["oWImages.autocatch.urlpattern", optionsCtrl._prefService.PREF_STRING, ""]);
  prefsToCheck.push(["oWImages.autocatch.any", optionsCtrl._prefService.PREF_BOOL, true]);
  prefsToCheck.push(["oWImages.autocatch.png", optionsCtrl._prefService.PREF_BOOL, true]);
  prefsToCheck.push(["oWImages.autocatch.gif", optionsCtrl._prefService.PREF_BOOL, true]);
  prefsToCheck.push(["oWImages.autocatch.jpg", optionsCtrl._prefService.PREF_BOOL, true]);
  prefsToCheck.push(["oWImages.autocatch.format.portrait", optionsCtrl._prefService.PREF_BOOL, true]);
  prefsToCheck.push(["oWImages.autocatch.format.landscape", optionsCtrl._prefService.PREF_BOOL, true]);
  prefsToCheck.push(["thumbnails.minHeight", optionsCtrl._prefService.PREF_INT, 20]);
  prefsToCheck.push(["thumbnails.minWidth", optionsCtrl._prefService.PREF_INT, 20]);
  prefsToCheck.push(["download.concurrent", optionsCtrl._prefService.PREF_INT, 5]);
  prefsToCheck.push(["oWImages.thumbnails.limit", optionsCtrl._prefService.PREF_INT, 1500]);
  prefsToCheck.push(["oWImages.allowBrowserJavascript", optionsCtrl._prefService.PREF_BOOL, true]);
  var root = optionsCtrl._prefService.getBranch("extensions.outwit.");
  var isDefault = true;

  isDefault = !optionsCtrl.autoRename;

  for(var i = 0 ; i < prefsToCheck.length && isDefault; 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;

};
