/* update with communication to new DomainService
 *
 *  update interaction with DomainService to access graph with specific permission on July 8
 *
 *  update code to JDK1.1 beginning on July 10 by Li, Qian.
 *
 *  add ACL control and read/write switching mechanism on July 20 by Li,Qian
 */
package graphbrowser;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

import java.util.*;
import java.net.*;
import java.lang.Math;
import java.io.*;

import graph.*;
import jowgraphservice.*;
import jow.*;


// *************************** GraphApplet **************************

public class GraphApplet extends Applet implements WindowListener {

  public static final String DEFAULT_SERVER = "tu-ppp-cs";
  public static  String JAVA_SERVER =null;

  private int numberWindows = 0;
  private boolean again = true;
  private URL url;
  private JOWGraphServiceInterface ds=null;
  //private String defaultURL = "http://jbspc.cs.unc.edu/0000";
  //protected UserID pid;
  public String userName;

  public boolean pasteMode=false;   // Paste Graph/Non Graph mode

  //public static int WorkMode=GraphEngine.NORMALMODE;
  public static GraphEngine graphEngine;

  public static Vector WindowList = new Vector();

  public static MyClipBoard clipboard= new MyClipBoard();

  public static Hashtable GraphRelationTable = new Hashtable();
  /** */

  public final static MIME_Type DEFAULT_TYPE = new MIME_Type ( MIME_Type.GRAPH, MIME_Type.NET );


  public void secTest() {
    String myFile="C:/foo";
    DataOutputStream dos;
    try {
  	  dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(myFile),128));
	  dos.writeChars("Cats can hypnotize you when you least expect it\n");
	  dos.flush();
	  System.out.println("Successfully wrote to the file named " + myFile + " -- go take a look at it!");

	  String name = System.getProperty("user.name");
	  System.out.println("And, successfully got user.name ..." + name);
	}
	catch (SecurityException e) {
	  System.out.println("writeFile: caught security exception");
        }
	catch (IOException ioe) {
		System.out.println("writeFile: caught i/o exception");
        }

  }


  public void init () {      // changed by Li, Qian on July,1
                             // enable user registration and access the default graph

/********  Initialization      **********/


// get applet parameters
    secTest();
    String rmiNaming=getParameter("GRAPHDOMAIN");
    String javaServer=getParameter("JAVASERVER");
    String rootGraph=getParameter("ROOTGRAPH");
    JAVA_SERVER = javaServer;

    System.out.println("GraphApplet: init");

    Graph newGraph=null;
    System.out.println("RMINaming:  " +rmiNaming);
    System.out.println("javaServer:  "+javaServer);
    System.out.println("rootGraph:  " +rootGraph);


    try {
        ds = (JOWGraphServiceInterface) new JOWService (javaServer,rmiNaming);

    } catch (JOWException e) {
        System.out.println("Graph Window: Build JOWService Fail");
        LabelDialog ld=new LabelDialog((Frame)this.getParent(),"Error Alarm","Error! Build JOWService Fail:"+e.getMessage());
        ld.show();
        //System.out.println("change to dummy server/debug model!!!");

      }



/*  registration window  */

    // *********** Qian: prompt user for UserID  default userID admin/admin


    MyDialog myd;

    boolean ok=false;

    // main control window
    Frame mainWin= new Frame("Main Window");
    mainWin.addWindowListener(this);
    //mainWin.show();

    if (ds==null) {
        System.out.println("No Server Support. Quit system.");
        LabelDialog ld=new LabelDialog(mainWin,"Error Alarm","No Server Support. Quit system.");
        ld.show();

        return; }


    String v1,v2;
    myd=new MyDialog( (Frame ) mainWin,"User Login Window");
    //myd=new MyDialog( (Frame) this.getParent(),"Input dialog");
     while (!ok) {
        myd.show();
        v1=myd.getValue1();
        v2=myd.getValue2();
        System.out.println("v1="+v1);
        System.out.println("v2="+v2);
        if (v1 != null ) {
          System.out.println("Register to server, please wait");

          // registration step
          try {
            ds.registerUser(new UserID(v1,v2) );
            ok=true;
            this.userName=v1;
          } catch (JOWException e3) {
             System.out.println("Registration failed");
             }
        }
        else { System.out.println("canceled");
                   this.destroy(); return; }
     }

    System.out.println("registration successful!");

  graphEngine = new GraphEngine(this);
  //System.out.println("After creatign graphengine");
    if (graphEngine==null) System.out.println("In GraphApplet Already null GraphEngine");


// load Rootgraph
   boolean readit =true;
    try {  // test
    boolean createit=false;
    if (readit) {
       try {
           URL url=new URL(rootGraph);
           newGraph= (Graph) ds.openGraph( url, GDPermissionImpl.READ );
           if (newGraph !=null) addGraphWindowForRead(ds,newGraph);
           else System.out.println("No graph available");
         } catch (JOWException e2) {
            System.out.println("Graph Applet open Graph for READ Fail:"+e2.getMessage());
        LabelDialog ld=new LabelDialog(mainWin,"Error Alarm","Graph Applet open Graph for READ Fail:"+e2.getMessage());
        ld.show();
            createit=true;
            }
           catch (MalformedURLException e) {
            System.out.println("Mal rootGraph URL");
           }

    }

    if (createit) {
      try {
       newGraph=(Graph) ds.createGraph();
        if (newGraph !=null) { newGraph.setLabel("Root"); addGraphWindow(ds,newGraph,true); }
       } catch (JOWException e3) {
            System.out.println("Graph Applet create Graph fail:"+e3.getMessage());
        LabelDialog ld=new LabelDialog(mainWin,"Error Alarm","Graph Applet create Graph fail:"+e3.getMessage());
        ld.show();
       }
    }
   }  catch (Exception e) { e.printStackTrace(); }

  }  // end init


  public void start () {
  }  // end start

  public void stop () {
  }  // end stop

  private URL getParam()  {
    URL u = null;
    String s;
    s = getParameter( "URL" );
    if ( s != null )
    try {
        u = new URL( s );
        }
    catch ( MalformedURLException e ) {
        System.out.println("MalformedURLException in GraphApplet.getParam");
        hide();
        stop();
    }  // end catch
    return u;
  }  // end getParam

  public void addGraphWindow( JOWGraphServiceInterface ds, URL url ) {
System.out.println("GraphApplet: addGraphWindow 1");
    GraphWindow gw = new GraphWindow ( this, ds, url );

    WindowList.addElement(gw);
    numberWindows++;
    gw.setMode(true);
    gw.start ();
  }  // end addGraphWindow


  public void addGraphWindow( JOWGraphServiceInterface ds, Graph g,boolean write) {
System.out.println("GraphApplet: addGraphWindow ");
    GraphWindow gw = new GraphWindow ( this, ds, g );
    WindowList.addElement(gw);
    numberWindows++;
    //System.out.println("Open Graph Label:"+g.getLabel());

    //String user=graphapplet.userName;
    gw.resetTitle();
    gw.start();
    gw.setMode(true);

  }  // end addGraphWindow


  public void addGraphWindow( JOWGraphServiceInterface ds, Graph g) {
System.out.println("GraphApplet: addGraphWindow ");
    GraphWindow gw = new GraphWindow ( this, ds, g );
    WindowList.addElement(gw);
    numberWindows++;
    //System.out.println("Open Graph Label:"+g.getLabel());

    //String user=graphapplet.userName;
    gw.resetTitle();
    gw.start ();
    gw.setMode(false);

  }  // end addGraphWindow


  public void addGraphWindowForRead( JOWGraphServiceInterface ds, Graph g ) {
    try {
System.out.println("GraphApplet: addGraphWindow ");
    GraphWindow gw = new GraphWindow ( this, ds, g );
    WindowList.addElement(gw);
    numberWindows++;
    //System.out.println("Open Graph Label:"+g.getLabel());
    //gw.setTitle("GraphWindow:"+g.getLabel());
    gw.setTitle("GraphWindow: "+"Username("+userName+") Graph:("+g.getLabel()+")");
    gw.start ();
    gw.setMode(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
  }  // end addGraphWindow

  public void addTextWindow( JOWGraphServiceInterface ds, URL u ) {
System.out.println("GraphApplet: addTextWindow 1");
    TextWindow tw = new TextWindow ( this, ds, url );
    //numberWindows++;
    tw.start ();
  }  // end addGraphWindow ( JOWGraphServiceInterface ds, URL u )

  public void addTextWindow( JOWGraphServiceInterface ds, Graph g, MIME_Type t ) {
System.out.println("GraphApplet: addTextWindow 1");
    TextWindow tw = new TextWindow ( this, ds, g, t );
    //numberWindows++;
    tw.start ();
  }  // end addGraphWindow ( JOWGraphServiceInterface ds, Graph g, MIME_Type t )

  public void addTextWindow( JOWGraphServiceInterface ds, ContentObject co ) {
System.out.println("GraphApplet: addTextWindow");
System.out.println("GraphApplet: MIME_Type="+(co.getType()).getType()+"/"+(co.getType()).getSubtype());
    TextWindow tw = new TextWindow ( this, ds, co );
    ///numberWindows++;
    tw.start ();
  }  // end addGraphWindow ( JOWGraphServiceInterface ds, Graph g, MIME_Type t )

  public void removeWindow (GraphWindow gw) {
    WindowList.removeElement(gw);
    gw.dispose();
    numberWindows--;
    if (numberWindows==0) { System.out.println("Quit the GraphApplet"); //System.exit(0);
                          }
  }  // end removeWindow



// new Event methods updated for JDK1.1

// implement the WindowListener interface
public void windowActivated(WindowEvent e) {
}

public void windowClosed(WindowEvent e) {
}

public void windowClosing(WindowEvent e) {
        /******************************/
        //((Frame) e.getSource()).dispose();
        //System.exit(0);
        /******************************/

}

public void windowDeactivated(WindowEvent e) {
}

public void windowDeiconified(WindowEvent e) {
}

public void windowIconified(WindowEvent e) {
}

public void windowOpened(WindowEvent e) {
}


////////////////////////////////////////////////////////////////////////
/////  New stuff for support of Cut/Copy/Paste
//public void setWorkMode(int workmode) {
//    WorkMode= workmode;
//}
  public JOWGraphServiceInterface getDomainService()
  {  return ds;
  }

  public GraphEngine getGraphEngine()
  {  return this.graphEngine;
  }

  public void menuEnabled(boolean mode) {
        System.out.println("Toggle the menu status");
        for ( Enumeration e1= WindowList.elements(); e1.hasMoreElements() ;) {
             ((GraphWindow) e1.nextElement()).setMenuEnabled(mode);
        }
  }

}  // end GraphApplet

