package gui.browser;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.awt.*;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

/**
 */


public class BrowserLogic {
  private Main b;
  private String fileName;
  LinkQueue lq = new LinkQueue();

  public BrowserLogic(Main _b) {
    b = _b;
  }


  /**
   *  When user click on "File:open",
   *  the openHtmlFile is invoked to open the selected gui.html file.
   */
  public void openHtmlFile() {
    File file = getInputFile("Select File");
    fileName = file.getAbsolutePath();
    String urlS = "file://localhost/" + fileName;
    processTextField(urlS);
  }

  /**
   *  When user click on "Forward",
   *  the forward method is invoked and it then calls
   *  the LinkQueue class.
   */

  public void forward() {
    setUrlNoException(lq.next());
  }

  /**
   *  When user click on "Backward",
   *  the Backward method is invoked and it then calls
   *  the LinkQueue class.
   */

  public void backward() {
    setUrlNoException(lq.previous());
  }

  public File getInputFile(String title) {
    FileDialog fd = new FileDialog(new Frame(), title);
    fd.setVisible(true);
    return new File(fd.getDirectory() +
                    fd.getFile());
  }

  public void setUrlNoException(URL u) {
    updateTextField(u.toString());
    new ThreadedLoad(b.getHtmlPane(), u);
  }

  public void updateTextField(String urlS) {
    b.setTextField(urlS);
  }

  public void processTextField(String s) {

    try {
      URL u = new URL(s);
      setUrl(u);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

  }

  /**
   *  hyperlinkPage method get invoked from BrowserListener
   *  to update the URL textField,
   *  to add the new url to the LinkQueue and
   *  to start an external thread that gui.run jep.setPage(url),
   */

  public void hyperlinkPage(JEditorPane jep, HyperlinkEvent e, JTextField tf) {
    URL url = e.getURL();
    lq.enQueue(url);
    updateTextField(url.toString());
    try {
      ThreadedLoad tl = new ThreadedLoad(jep, url);
    } catch (Throwable t) {
      System.out.println("could not open:" + url);
    }
  }

  /**
   *  setUrl method is invoked to start an external thread that
   *  gui.run jep.setPage(url),
   *  update the URL textField and
   *  add the new url to the LinkQueue and
   */


  public void setUrl(URL u) {
    new ThreadedLoad(b.getHtmlPane(), u);
    updateTextField(u.toString());
    lq.enQueue(u);
  }
}