package com.Series40Book.midp.model;

import com.Series40Book.midp.controller.*;
import javax.microedition.io.*;
import java.io.*;

/**
 * A gateway to the Google facade server
 */
public class GoogleBrowser {

  public static String spellSugg;
  public static String [] urls;
  public static String [] snippets;
  private static String serverurl;

  private GoogleBrowser () {
  }

  public static void init (String u) {
    serverurl = u;
    spellSugg = "No Suggestion";
    urls = new String [0];
    snippets = new String [0];
  }

  public static void search (String keywords,
       boolean isPhrase, int maxBuffer, int maxResults,
             WorkerRunnable worker) throws Exception {
    HttpConnection conn = null;
    DataInputStream hdin = null;
    DataOutputStream hdout = null;

    try {
      worker.updateWaitStatus ("Opening connection");
      conn = (HttpConnection) Connector.open(serverurl);
      conn.setRequestMethod(HttpConnection.POST);
      hdout = conn.openDataOutputStream();
      worker.updateWaitStatus ("Sending request");
      hdout.writeInt(OpCodes.GOOGLE); // Submit opcode
      hdout.writeUTF(keywords);
      hdout.writeBoolean(isPhrase);
      hdout.writeInt(maxBuffer);
      hdout.writeInt(maxResults);
      hdout.flush();

      worker.updateWaitStatus ("Spell checking");
      hdin = conn.openDataInputStream();
      spellSugg = hdin.readUTF();
      int size = hdin.readInt();
      snippets = new String [size];
      urls = new String [size];

      for (int i = 0; i < size; i++) {
        worker.updateWaitStatus ("Downloading item "+i);
        urls[i] = hdin.readUTF();
        snippets[i] = hdin.readUTF();
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception ("Connection error");
    } finally {
      try {
        if (conn != null) conn.close();
        if (hdout != null) hdout.close();
        if (hdin != null) hdin.close();
      } catch (Exception e) {}
    }
  }

}
