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

/**
 * @name autocatchRule
 * @static
 * Super simple class trying to check if
 * an imagee (aka aBean) fit the rule 
 * edict by the user to automatically
 * catch her.
 */
var autocatchRule = {};


/**
 * @name autocatchRule.testRule
 * @static
 * Check if an image (aBean) passed all the
 * user setup.
 * @param {object} aBean
 *
 *
 */
autocatchRule.testRule = function( aBean ){

//dump("###############################################################\n");

  // ### Check type of image (png, jpg, gif, ...)
  //if (!any)
  if (!ow.app.kernel.prefs.getBool("oWImages.autocatch.any", "")) {
    var imageType = aBean.filename.split(".");
    imageType = imageType[imageType.length-1];
    var types = ['png', 'gif', 'jpg']; // XXX only change this if more types added
    var found = false;
    for (var i = 0, curTypePref; i < types.length; ++i) {
      curTypePref = ow.app.kernel.prefs.getBool("oWImages.autocatch." + types[i], "");
      
      if(types[i] == "jpg"){ //XXX dummy patch
        if (imageType.toLowerCase() == "jpeg") {
          found = curTypePref;
          break;
        }
      }
      if (imageType.toLowerCase() == types[i]) {
        found = curTypePref;
        break;
      }
    }
//dump(">>>>> TYPE : NOT ANY - " + aBean.filename + " - " + found + "\n");
    if (!found) {
      return false;
    }
  }
//  else {
//dump(">>>>> TYPE : ANY - " + aBean.filename + "\n");
//  }
  
//dump(">>> ### TYPE TEST PASSED\n");

  // Check if url contains pattern (string/regexp)
  var urlpattern = ow.app.kernel.prefs.getString("oWImages.autocatch.urlpattern", "");
  if(urlpattern != ""){ //we have a filter on this
    var reg = new RegExp(urlpattern, "gi");
    if(aBean.mediaUrl.search(reg) == -1)
      return false;
  }
//dump(">>> ### URL TEST PASSED\n");

  // Check image size condition
  var [strImgWidth, strImgHeight] = aBean.size.split(/\s*x\s*/);
  var imgWidth = parseInt(strImgWidth);
  var imgHeight = parseInt(strImgHeight);

//dump("RATIO TEST : " + aBean.size + " " + imgWidth + " " + imgHeight + " - " + ow.app.kernel.prefs.getBool("oWImages.autocatch.format.portrait", "") + " - " + ow.app.kernel.prefs.getBool("oWImages.autocatch.format.landscape", "") + "\n");
//
  if ((!ow.app.kernel.prefs.getBool("oWImages.autocatch.format.portrait", "") && imgWidth < imgHeight)
      || (!ow.app.kernel.prefs.getBool("oWImages.autocatch.format.landscape", "") && imgWidth > imgHeight)) {
    return false;
  }

  //Check if the image is displayed
  if( imgWidth < ow.app.kernel.prefs.getInt("extensions.outwit.thumbnails.minWidth", 20) || imgHeight < ow.app.kernel.prefs.getInt("extensions.outwit.thumbnails.minHeight",20)){
    return false;
  }

//dump(">>> ### RATIO TEST PASSED\n");

  var nbConditions = 2; // XXX only change this if more condition lines :)
  var comparators = ['>', '==', '<']; // XXX this must match options index order
  var theFinalTest = "";
  for (var i = 1, prefValue, strPrefixPref, prefComparator; i <= nbConditions; ++i) {
    strPrefixPref = "oWImages.autocatch.cond" + i + ".";
    prefValue = ow.app.kernel.prefs.getInt(strPrefixPref + "size", -1);
    if (prefValue != -1) {
      prefComparator = comparators[ow.app.kernel.prefs.getInt(strPrefixPref + "comparator", -1)];
      switch (ow.app.kernel.prefs.getInt(strPrefixPref + "condition", -1)) {
        // these must match options index order
        case 3: // "width is"
          theFinalTest += "("+imgWidth + prefComparator + prefValue + ")";
          break;
        case 2: // "height is"
          theFinalTest += "("+imgHeight + prefComparator + prefValue + ")";
          break;
        case 0: // "width and height are"
          theFinalTest += "(("+imgWidth + prefComparator + prefValue
                   + ") && ("+imgHeight + prefComparator + prefValue + "))";
          break;
        case 1: // "width or height are"
          theFinalTest += "(("+imgWidth + prefComparator + prefValue
                   + ") || ("+imgHeight + prefComparator + prefValue + "))";
          break;
      }
      theFinalTest += "&&";
    }
  }
  theFinalTest = theFinalTest.substr(0, theFinalTest.length -2);

//  alert(aBean.size + " " + aBean.mediaUrl + " " + imgWidth + " " + imgHeight + "  " + theFinalTest);

  var sandBox = new Components.utils.Sandbox('about:blank');
  var result  = (Components.utils.evalInSandbox(theFinalTest, sandBox) === true);
  
  //dump(">>>>>> SIZE : " + aBean.size + " - " + theFinalTest + " - " + result + "\n");

  if (theFinalTest && !result) return false;

  return true;
};

autocatchRule.execRule = function(){
  var items = document.getElementById('owImagesContainer').thumbs._itemsDisplayed;
  for(let i = 0 ; i < items.length ;i++){
    if (this.testRule(items[i])){
      items[i].type = 'image';
      coreKit.coreMessager.observe('CATCH', 1, 1, '', items[i]);
    }
  }
};
