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

/**
 *
 * imageEngineService is one of the wheel
 * of Outwit-Images. 
 * We use it to create dynammicaly new search engine for
 * the user depending on the search engine it use.
 *
 * This is a bit 'weird' but it is probably the best 
 * way to create an independent search engine.
 */



/********
 * XXX Discover url arguments
 * XXX use a temporary place to store these informations
 * XXX got a cofee after all these steps
 */


/**
 * @name imageEngineService
 * @static
 * This is the base static class for the image
 * search engine discovery.
 * We presume image search engine contain
 * the word /images?\./ somewhere
 * So we try hard to discover it
 */
var imageEngineService = {};

imageEngineService.SEARCH_PARAM = "g" + String.fromCharCode(98) + "v";
imageEngineService.SEARCH_PARAM_VALUE = "1";

imageEngineService.currentURI = null;

/**
 * @name imageEngineService.textSource
 * @static
 * The text representation of the current source
 * Mainly used to discover focus() on it.
 * It seems that all search engine use this embedded
 * on their page to prevent some unuseful http request.
 */
imageEngineService.textSource = "";


/**
 * @name imageEngineService.currentURI
 * @static
 * The nsIURI for this session.
 * May change during the extracting process.
 */
imageEngineService.currentURI;

/**
 * @private
 * Internal pattern use to check the currentURI
 */
imageEngineService._regURL = /.*[\/.]images?.*/gi;


/**
 * @private
 * Internal pattern use to discover focus() in script
 */
imageEngineService._regFocus = /[a-z0-9_"'\.\(\)]*\.focus\(\)/i;


/**
 * @private
 * Search throught the links of the documents
 * one or more interesting links.
 * XXX for now we hope to find only one
 */
imageEngineService._probableURL = function( someLinks ){
  function containImage(element, index, array) {
    element += "";
    return (element.search(imageEngineService._regURL) != -1);
   }

   function isSameDomain(element, index, array){
      var url = widgets.page.browser.currentURI.host;
      var checkURL = url.match(/([^.]+\.[^.]+)$/).pop();
      var baseURL = Components.classes["@mozilla.org/network/io-service;1"]
                    .getService(Components.interfaces.nsIIOService)
                    .newURI(element + "", null, null)
      var checkBaseURL = baseURL.host.match(/([^.]+\.[^.]+)$/).pop();

      return (checkURL.toLowerCase() == checkBaseURL.toLowerCase());
   };
   function removeMyself(element, index, array){};

	 function textIsMatching(element, index, array) {
     return /^[^\w]*(?:Images|Imagens|Im\xE1genes|Immagini|Bilder|Billeder|\u56FE\u7247|Afbeeldingen|\u0635\u0648\u0631|\u041A\u0430\u0440\u0442\u0438\u043D\u043A\u0438|Kuvahaku|\u05EA\u05DE\u05D5\u05E0\u05D5\u05EA|Grafika)[^\w]*$/i.test(element.textContent);
		 // (Images|Imagens|Imágenes|Immagini|Bilder|Billeder|图片|Afbeeldingen|صور|Картинки|Kuvahaku|תמונות|Grafika)
	 }

	 //return someLinks.filter(textIsMatching).concat(someLinks.filter(containImage).filter(isSameDomain));
	 return someLinks.filter(textIsMatching).concat(someLinks.filter(containImage).filter(isSameDomain)).map(function(elt) { return (elt.href.indexOf("?") != -1 && !ow.app.kernel.prefs.getBool("oWImages.allowBrowserJavascript", true) ? elt.href + "&" + imageEngineService.SEARCH_PARAM + "=" + imageEngineService.SEARCH_PARAM_VALUE : elt.href); });  
};


/**
 * @private
 * Return the most probable HTMLInputElement
 * (if any)
 */
imageEngineService._probableInputElement = function( aDOM ){
  this.textSource = aDOM.documentElement.innerHTML;
  var jsResult = this.textSource.match(this._regFocus);
  if(jsResult){
    jsResult = jsResult[0].replace(".focus()", "").replace("document.", "");
    
    // Find a way to get the search box
    var element = null;
    try{
      element = aDom[jsResult];
    }
    catch(e){
    }
    if(!element){
      try{
        element = aDOM.wrappedJSObject[jsResult];
      }
      catch(e){
      }
    }
    if(!element){ //nothing found? brute force javascript!
      try{
        element = aDOM.defaultView[jsResult];
      }
      catch(e){
      }
      if(!element){
        try{
          element = aDOM.defaultView.wrappedJSObject[jsResult];
        }
        catch(e){
        }
      }
    }
    return element;
  }
  return null;
};


/**
 * @private
 * Simulate keyboard to do:
 *  - Custom search for guess who is the image engine
 *  - User search
 */
imageEngineService._simulateKeyboard = function(aDOM, anElement, aString ){
  for(var i=0;i<aString.length;i++){
    var event = aDOM.createEvent("KeyboardEvent");
    event.initKeyEvent("keypress",true,true,null,false,false,false,false,aString.charCodeAt(i),aString.charCodeAt(i));
    anElement.dispatchEvent(event);
  }
  var event = aDOM.createEvent("KeyboardEvent");
  event.initKeyEvent("keypress",true,true,null,false,false,false,false,13,13);
  anElement.dispatchEvent(event);
}


/**
 * @name imageEngineService.discover
 * @static
 * Try to find the images part of this
 * open search engine.
 */

imageEngineService.get = function(){
  var source = widgets.page.browser.contentDocument;
  var url = widgets.page.browser.currentURI.spec;
  var isImageURL = url.search(this._regURL);
  if (isImageURL == -1){
    //at this point, we are not sure this search engine if
    //an engine to search image.
    //So we try to search one in the page
    var HTMLlinks = source.links;
    var links = [];
    for(var i = 0 ; i<HTMLlinks.length ; i++)
      links.push(HTMLlinks.item(i));
    links = this._probableURL(links);

    if(links.length >= 2){//ouhhhh!!! take the first one for now
      outwitImages.UIControls.mode = outwitImages.UIControls.MODE_URL;
      this.loadURI(links[0], this.data, this.postData, this.uuu, this.userSearch);
    }
    else if(links.length == 1){ //probably found it : yeahhh 
      outwitImages.UIControls.mode = outwitImages.UIControls.MODE_URL;
      this.loadURI(links[0], this.data, this.postData, this.uuu, this.userSearch);
    }
    else if(links.length == 0 ){
      //We don't find images but try it harder
      //don't desesperate, try the hard way
      var element = this._probableInputElement(source);
      if(element){ //we have found something, look closer
        this._simulateKeyboard( source, element, this.userSearch );
      }
      else{
        //we have found nothing interesting
        //do the user search
        outwitImages.UIControls.mode = outwitImages.UIControls.MODE_URL;
        widgets.page.reload();
      }
    }
  }
  else{ //just do the user search
    outwitImages.UIControls.mode = outwitImages.UIControls.MODE_URL;
    widgets.page.reload();
  }
};




imageEngineService.loadURI = function(url, data, postData, uuu, userSearch){
    this.data = data;
    this.postData = postData;
    this.uuu = uuu;
    this.parameters = [url, data, postData, uuu];
    this.userSearch = userSearch;
    this.currentURI = null;
    outwitImages.browserControls.loadURI(url);
};


