/**
 * @author	Emmanuel Languillat
 */

import java.applet.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import com.sun.java.swing.*;
import java.net.*;
import java.io.*;

public class Explorer {

  WebTreePanel   treepanel; /* panel de l'arborscence des repertoires */
  HtmlPanel      htmlpanel; /* panel html */
  WebTree        webtree;   /* arborescence logique du site web */
  URLBar         urlbar;    /* barre de saisie de l'url */
  TreeParser     p;         /* parser de pages html */
  JSplitPane     splitpane; /* le panel coupe en deux */
  WebMenuBar     webmenubar;
  WebButtonBar   webbuttonbar;

  int            browsermode  = 1; /* mode du browser large icon/small icon/list icon */
  String         directorySav = "";
  String         hostname;
  boolean        exploreParent = false;
  ExplorerThread exThr;
  JFrame	 frame;
  
  void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {
    gbc.gridx      = gx;
    gbc.gridy      = gy;
    gbc.gridwidth  = gw;
    gbc.gridheight = gh;
    gbc.weightx    = wx;
    gbc.weighty    = wy;
  }

  public void destroy() {
    frame.removeAll();
	 frame.setVisible(false);
    SiteMapper.deref();
    exThr.stop();
    exThr=null;
  }
  
  public Explorer(ExplorerThread daddy) {
	 exThr = daddy;
    /* declaration */
    frame                   = new JFrame("SiteMapper"); /* fenetre */
    JPanel panel                   = new JPanel(true);         /* Panel principal */
    GridBagLayout gridBag          = new GridBagLayout();      /* layout */
    GridBagConstraints constraints = new GridBagConstraints(); /* contraintes du layout */
    
    frame.getContentPane().add("Center",panel);                /* ajouter le panel */
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
	System.exit(0);
      }
    });
    
    panel.setLayout(gridBag);   /* affecter le gridBag au panel principal */

    /* barre de menu */
    webmenubar = new WebMenuBar(this);
    frame.setJMenuBar(webmenubar);

    /* barre de boutons */
    constraints.fill = GridBagConstraints.BOTH;
    buildConstraints(constraints,0,0,1,1,100,0);
    webbuttonbar = new WebButtonBar( this );
    gridBag.setConstraints(webbuttonbar,constraints);
    panel.add(webbuttonbar);
    
    /* barre de l'url */
    constraints.fill = GridBagConstraints.BOTH;
    buildConstraints(constraints,0,1,1,1,100,0);
    urlbar = new URLBar( this );
    gridBag.setConstraints(urlbar,constraints);
    panel.add(urlbar);
    
    /* Arborescence */
    treepanel = new WebTreePanel( this );
    
    /* browser */
    htmlpanel = new HtmlPanel();
    
    /* Representation du site */
    constraints.fill = GridBagConstraints.BOTH;
    buildConstraints(constraints,0,2,1,1,100,90) ;
    splitpane = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT,treepanel,htmlpanel);
    splitpane.setContinuousLayout(false);
    gridBag.setConstraints (splitpane, constraints);
    panel.add(splitpane);

    /* pack */
    panel.setPreferredSize(new Dimension(700, 600));

    frame.pack();
    frame.setVisible(true);

  }

  public void ChangeURL(String website) {
    try {
      URL test = new URL(website);
    }
    catch(Exception e) {
      return;
    }
    
    System.out.println("Web> "+website);
    if(p!=null) {
      p.stop();
      p = null;
    }
   

    // run();
    
    URL url      = null;
    try {
      url     = new URL(website);
      webtree = new WebTree(new Info(url.getHost(), 0, "WebSite Name", "", 0));
      p       = new TreeParser(this, url, exploreParent);
      hostname = url.getHost();
    }
    catch(MalformedURLException e) {
      System.err.println("Malformed URL");
    }
    
    treepanel.AddHost(url.getHost());
    webbuttonbar.enabledStop();
    p.start();

    /*try {
      p.join();
      }
      catch( InterruptedException e ) {
      System.err.println("Error interrupted");
      }
      webtree.display();*/
  }
  
  public void run () {
    PipedReader wIn;
    PipedWriter wOut;
    try {
      wIn  = new PipedReader();
      wOut = new PipedWriter(wIn);

      wOut.write("<HTML><HEAD></HEAD><BODY>");
      wOut.write("<H1>Les liens ne marchent pas correctement</H1>");
      wOut.write("<TABLE BORDER=1><TR><TD>yoyo</TD><TD>toto</TD></TR><TR><TD>tutu</TD></TR></TABLE>titi");
      wOut.write("<A HREF=http://www.essi.fr/~languill>Manu's HomePage</A><P>");
      wOut.write("</BODY></HTML>");

      wOut.flush();
      wOut.close();

      htmlpanel.setText(wIn);
      wIn.close();
    }
    catch(IOException e) {
      System.err.println("Unable to process communication.");
    }
  }

  public void loadBrowser( String directory) {

    JScrollPane    jsp = new JScrollPane();
    directorySav = directory;
    
    if (browsermode == 1 ) {
      LargeIconPanel lip = new LargeIconPanel( this, webtree, directory);
      jsp = new JScrollPane(lip);
    }
    
    if (browsermode == 2 ) {
      SmallIconPanel sip = new SmallIconPanel( this, webtree, directory);
      jsp = new JScrollPane(sip);
    }

    if (browsermode == 3 ) {
      ListIconPanel lip  = new ListIconPanel( this, webtree, directory);
      jsp = new JScrollPane(lip);
    }


    splitpane.remove(splitpane.getRightComponent());
    splitpane.setRightComponent(jsp);
    splitpane.setVisible(true);
    splitpane.doLayout();
    splitpane.updateUI();
  }

  public void changeMode(int mode) {
    /* permet de changer le mode d'affichage des fichiers 
       mode 1 : grandes icones
       mode 2 : petites icones
       mode 3 : liste */
    browsermode = mode;
    loadBrowser(directorySav);
  }

  public void upDirectory() {
    /* permet de remonter d'un niveau dans l'arborescence 
       l'ordre est passe au treepanel */
    treepanel.upToNode();
  }

  public void downDirectory(String path, String directory) {
    /* permet de descendre d'un niveau dans l'arborescence
       l'ordre est passe au treepanel */
    treepanel.downToNode(path, directory);
	 loadBrowser(path + directory +'/');
  }

  public void openURL(String path, String page) {

    String    url = "http://";

    url = url.concat(hostname);
    url = url.concat("/");
    url = url.concat(path);
    url = url.concat(page);

    splitpane.remove(splitpane.getRightComponent());
    htmlpanel  = new HtmlPanel(url);
    splitpane.setRightComponent(htmlpanel);
    splitpane.setVisible(true);
    splitpane.doLayout();
    splitpane.updateUI();
  }

  public void openFILE(String path, String page) {
    String url = "http://";
 
    url = url.concat(hostname);
    url = url.concat("/");
    url = url.concat(path);
    url = url.concat(page);

    splitpane.remove(splitpane.getRightComponent());
    htmlpanel  = new HtmlPanel();

    PipedReader wIn;
    PipedWriter wOut;
    try {
      wIn  = new PipedReader();
      wOut = new PipedWriter(wIn);
 
      wOut.write("<HTML><HEAD></HEAD><BODY>");
      wOut.write("<IMG SRC=");
		wOut.write(url);
		wOut.write(">");
      wOut.write("</BODY></HTML>");
 
      wOut.flush();
      wOut.close();
 
      htmlpanel.setText(wIn);
      wIn.close();
    }
    catch(IOException e) {
      System.err.println("Unable to process communication.");
    }

    splitpane.setRightComponent(htmlpanel);
    splitpane.setVisible(true);
    splitpane.doLayout();
    splitpane.updateUI();
  }

  public void openTXT(String path, String page) {
    String url = "http://";
 
    url = url.concat(hostname);
    url = url.concat("/");
    url = url.concat(path);
    url = url.concat(page);

    splitpane.remove(splitpane.getRightComponent());
    JTextArea textPanel = new JTextArea();
    textPanel.setEditable(false);

    try {
		URL url1 = new URL(url);
    	BufferedReader in = new BufferedReader(
									new InputStreamReader(url1.openStream()));
		String s;
      while( (s = in.readLine()) != null ) textPanel.append(s +'\n');
    }
    catch(Exception e) {
      System.err.println("Error while communication");
    }
 
    JScrollPane jsp = new JScrollPane(textPanel);
    splitpane.setRightComponent(jsp);
    splitpane.setVisible(true);
    splitpane.doLayout();
    splitpane.updateUI();
  }

  public void openApplet(String path, String page) {
    String url = "http://";
 
    url = url.concat(hostname);
    url = url.concat("/");
    url = url.concat(path);
    url = url.concat(page);
 
    splitpane.remove(splitpane.getRightComponent());

    appletLoader loader = new appletLoader(url);

    Applet app = loader.getApplet();

    if( app!=null ) {
    	JScrollPane jsp = new JScrollPane(app);
      app.init();
      app.start();
    	splitpane.setRightComponent(jsp);
    }
    else splitpane.setRightComponent(new Label("This is not an Applet"));
    splitpane.setVisible(true);
    splitpane.doLayout();
    splitpane.updateUI();
  }

  public void setExploreParent(boolean b) {
      exploreParent = b;
  }
 
  public void stopParser() {
    if(p!=null) {
      p.stop();
      p = null;
    }
    webbuttonbar.disabledStop();
  }

  public void endParsing() {
    /* notification d'arret du parser */
    webbuttonbar.disabledStop();
  }

  public void notify(Info info) {
    /* notification d'ajout d'un nouvel element de la part du parser */
    webtree.add(info);
    treepanel.AddDirectory(info);
  }
}
