package com.buzzphone.server.Google;

import java.util.*;

/**
 * The facade in front of the Google web services.
 */
public class Facade {

  public String spellSugg;
  public String [] snippets;
  public String [] urls;

  private String key;

  public Facade (String k) {
    key = k;
  }

  public void getResults (String keywords,
     boolean isPhrase, int maxBuffer, int maxResults) {
    try {
      String query = keywords;
      if (isPhrase) {
        query = reformatPhraseQuery(keywords);
      }

      spellSugg = GoogleUtil.getSpellSugg(key, query);
      if (spellSugg == null || "".equals(spellSugg)
                            || "null".equals(spellSugg)) {
        spellSugg = "The spelling is correct";
      }
      urls = GoogleUtil.search(key, query, maxResults);
      snippets = new String [urls.length];

      for (int i = 0; i < urls.length; i++) {
        String cache = GoogleUtil.getCache(key, urls[i]);
        cache = stripTags(cache);
        String snippet = cutSnippet (cache, maxBuffer,
                                     keywords, isPhrase);
        if (snippet == null || "".equals(snippet)) {
          snippets[i] = "No snippet";
        } else {
          snippets[i] = snippet;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error in getResults");
      spellSugg = "error";
      snippets = null;
    }
  }

  private String reformatPhraseQuery (String keywords) {
    StringTokenizer st = new StringTokenizer(keywords);
    StringBuffer sb = new StringBuffer ();
    sb.append("\"");
    while (st.hasMoreTokens()) {
      sb.append("+").append(st.nextToken()).append(" ");
    }
    String result = sb.toString().trim();
    result = result + "\"";
    return result;
  }

  private String stripTags (String cache) {
    StringBuffer cacheBuffer = new StringBuffer(cache);
    int start, end;
    while ((start = cacheBuffer.indexOf("<")) != -1) {
      end = cacheBuffer.indexOf(">", start);
      if (end == -1) {
        break;
      } else {
        cacheBuffer.replace(start, end + 1, " ");
      }
    }
    if ((end = cacheBuffer.indexOf(
                 "responsible for its content.")) != -1){
      end = end + 29;
      cacheBuffer.replace(0, end, "");
    }
    while ((start = cacheBuffer.indexOf("\n")) != -1 ||
           (start = cacheBuffer.indexOf("\r")) != -1 ||
           (start = cacheBuffer.indexOf("\t")) != -1) {
      end = start + 1;
      cacheBuffer.replace(start, end, " ");
    }
    while ((start = cacheBuffer.indexOf("&nbsp;")) !=-1){
      end = start + 6;
      cacheBuffer.replace(start, end, " ");
    }
    while ((start = cacheBuffer.indexOf("  ")) != -1) {
      end = start + 2;
      cacheBuffer.replace(start, end, " ");
    }
    return cacheBuffer.toString().trim();
  }

  private String cutSnippet (String cache, int maxBuffer,
                   String keywords, boolean isPhrase) {
    int start = 0;
    int end = 0;
    int index = -1;
    if (isPhrase) {
      index = cache.toUpperCase().indexOf(
                         keywords.toUpperCase());
      if ( index != -1) {
        index += keywords.length() / 2;
      }
    } else {
      StringTokenizer st = new StringTokenizer(keywords);
      while (st.hasMoreTokens()) {
        String word = st.nextToken ();
        index = cache.toUpperCase().indexOf(
                            word.toUpperCase());
        if (index != -1) {
          index = index + word.length() / 2;
          break;
        }
      }
    }

    if (index == -1) {
      return null;
    }

    start = index - maxBuffer / 2;
    end = index + maxBuffer / 2;
    if (start < 0) start = 0;
    if (end > cache.length() - 1)
          end = cache.length() - 1;

    return cache.substring(start, end);
  }

}
