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

/**
 * @name autocatchRule
 * @static
 * Super simple class trying to check if
 * a document fit the rule 
 * edict by the user to automatically
 * catch it.
 */
var autocatchRule = {};


/**
 * @name autocatchRule.testRule
 * @static
 * Check if an image (aBean) passed all the
 * user setup.
 * @param {object} aBean
 *
 *
 */
autocatchRule.testRule = function( aBean ){
  // ### Check type of doc (pdf, doc, xls, ...)
  //if (!any)
  //XXX Do good stuff here
  if (!ow.app.kernel.prefs.getBool("oWDocs.autocatch.any", "")) {
    var documentType = aBean.filename.split(".");
    documentType = documentType[documentType.length-1];
    documentType = documentType.toLowerCase();
    //'text':['txt', 'rtf'],
    var types = {
      'documents':['doc','docx','odt','pdf', 'txt','rtf', 'sxw'],
      'datasheets':['xls', 'xlsx', 'sxc', 'ods'],
      'presentations':['ppt', 'pps','pptx', 'ppsx','swf']
    }
    var found = false;
    for( var type in types ){
      var toCheck = ow.app.kernel.prefs.getBool("oWDocs.autocatch." + type, "");
      if( toCheck ) {
        var subTypes = types[type];
        for( var i = 0 ; i < subTypes.length ; i++ ){
          if (documentType == subTypes[i]) {
            found = true;
            break;
          }
        }
      }
    }
    
    if (!found) {
      return false;
    }
  }


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

  return true;
};


autocatchRule.execRule = function(){
  var items = gFolder.items;
  for(let i = 0 ; i < items.length ;i++){
    if (this.testRule(items[i])){
      coreKit.coreMessager.observe('CATCH', 1, 1, '', items[i]);
    }
  }
};

