//
// A Java client interface for talking to the LPC logic engine.
//
//
//    Copyright (C) 2000 by Hugh Jack <jackh@gvsu.edu>
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program; if not, write to the Free Software
//    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//
// Last Modified: October 12, 2000
//

// package LPC;

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


import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;  
import javax.xml.parsers.ParserConfigurationException;  
import javax.xml.parsers.SAXParser;


public class LPCclient extends Applet implements Runnable{
	Label			none;

	// Server and login Info
	Font 			myfont;
	Button			login_button;
	TextField		server_name;
	TextField		server_socket;
	TextField		user_name;
	TextField		user_password;
	TextArea		status;
	TextArea		put_text;

	// general requests
	Button			get_button;
	Button			version_button;
	Button			disconnect_button;
	Button			status_button;
	Button			run_button;
	Button			idle_button;
	Button			reboot_button;
	Button			upload_button;
	Button			clear_button;

        String          out=null;
	Message			SYNC;
	int			connect;
	// int			wait_for_reply;
	Communications	io_monitor;

	public void init() {
	
		// Set up GUI window
		Panel p = new Panel() ;    
                setBackground(Color.white);
                p.setLayout(new GridLayout(2,2)); //,2,10));
 		myfont = new Font("Times",Font.PLAIN,12);
			setFont(myfont);

		none = new Label("Server");	
			p.add(none);
		server_name = new TextField();
			p.add(server_name);
			server_name.setText("148.61.36.49");
			//server_name.setText("localhost");
		none = new Label("Socket");	
			p.add(none);
		server_socket = new TextField();
			p.add(server_socket);
			server_socket.setText("1237");
		none = new Label("User name");	
			p.add(none);
		user_name = new TextField();
			p.add(user_name);
			user_name.setText("Huffin");
		none = new Label("Password");	
			p.add(none);
		user_password = new TextField();
			p.add(user_password);
			user_password.setText("Puffin");

		login_button = new Button("Login");
			p.add(login_button);
		version_button = new Button("Version");
			p.add(version_button);
		get_button = new Button("Get File");
			p.add(get_button);
		upload_button = new Button("Upload");
			p.add(upload_button);
		status_button = new Button("Status");
			p.add(status_button);
		run_button = new Button("Run");
			p.add(run_button);
		idle_button = new Button("Idle");
			p.add(idle_button);
		disconnect_button = new Button("Logout");
			p.add(disconnect_button);
		reboot_button = new Button("Reboot");
			p.add(reboot_button);
		clear_button = new Button("Clear");
			p.add(clear_button);

		setLayout(new BorderLayout());
		add("North", p) ;

		status = new TextArea("Log Window\n", 15,50);
			add("Center", status);
			// p.add(status);
		put_text = new TextArea("<plc>\n\t<memory>\n\t\t<set name=\"start\" value=\"1\"/>\n\t</memory>\n</plc>\n", 15,50);
			add("South", put_text);
			//p.add(status);


		//
		// Set up communications
		//
		SYNC = new Message();
		connect = 0;
		// wait_for_reply = 0;

		// SYNC.startclient("localhost", 1238);
		// sync_read_flag = 0;
		// sync_write_flag = 0;

		//
		// Start communications monitor thread
		// 
		io_monitor = new Communications();
		io_monitor.start();

System.out.println("ZZZ\n"); System.out.flush();
		Xml_store	tester;
System.out.println("AAA\n"); System.out.flush();
		tester = new Xml_store();
System.out.println("BBB\n"); System.out.flush();
		tester.parse_xml("test.plc");
System.out.println("CCC\n"); System.out.flush();
		tester.dump_xml();
System.out.println("DDD\n"); System.out.flush();
	}


  	public void start(){
  	}

		
 	public void repaint(){
		super.repaint();
  	}

	public void run(){
		status.append("The client has started, please login to the LPC before using other commands");
	}

	public void stop(){
		if(connect > 0){
			connect = 0;
			SYNC.disconnect(SYNC.READ + SYNC.WRITE);
			status.append("Disconnected from LPC\n");
		}
	}

	public void destroy(){
		SYNC.disconnect(SYNC.CLIENT);
	}

       

	// mouse actions
        public boolean action(Event evtObj, Object arg){
		int		temp1;

        	if (evtObj.target instanceof Button){ 
			if(arg.equals("Login")){
				if(connect > 0){
					connect = 0;
					SYNC.disconnect(SYNC.READ);
					SYNC.disconnect(SYNC.WRITE);
					status.append("Disconnected from LPC\n");
				}
				try{
					temp1 = Integer.parseInt(server_socket.getText());
					SYNC.startclient(server_name.getText(), temp1);
					if((SYNC.connect(SYNC.WRITE) == SYNC.NO_ERROR) && (SYNC.connect(SYNC.READ) == SYNC.NO_ERROR)){
						status.append("Connection to LPC now active\n");
						connect = 1;
					} else {
						status.append("Connection was refused - the LPC might be busy\n");
					}
				} catch (Exception f) {
					status.append("Problems connecting to server\n");
				}
				if(connect == 1){
					try{
						SYNC.send_string("USER "+user_name.getText()+"\n");
						io_monitor.wait_for_reply = 1;
						while(io_monitor.wait_for_reply == 1){};
						if(io_monitor.wait_for_reply < 1){
							SYNC.send_string("PASS "+user_password.getText()+"\n");
							io_monitor.wait_for_reply = 1;
							while(io_monitor.wait_for_reply == 1){};
							if(io_monitor.wait_for_reply < 1){
								connect = 2;
							} else {
								status.append("User or Password incorrect - disconnected from LPC\n");
							}
						} else {
							status.append("User or Password incorrect - disconnected from LPC\n");
						}
					} catch (Exception f) {
						status.append("Problems sending login string\n");
					}
				}
				if(connect < 2){
					connect = 0;
					SYNC.disconnect(SYNC.READ);
					SYNC.disconnect(SYNC.WRITE);
					// status.append("User or Password incorrect - disconnected from LPC\n");
				}

				return true;
			} else if(arg.equals("Get File")){
				if(connect == 2){
					try{
						SYNC.send_string("GET\n");
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			} else if(arg.equals("Logout")){
				if(connect == 2){
					try{
						status.append("logging out of LPC server\n");
						SYNC.send_string("DISCONNECT\n");
						connect = 0;
						SYNC.disconnect(SYNC.READ);
						SYNC.disconnect(SYNC.WRITE);						
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			} else if(arg.equals("Status")){
				if(connect == 2){
					try{
						SYNC.send_string("STATUS\n");
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			} else if(arg.equals("Version")){
				if(connect == 2){
					try{
						SYNC.send_string("VERSION\n");
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			} else if(arg.equals("Run")){
				if(connect == 2){
					try{
						SYNC.send_string("RUN\n");
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			} else if(arg.equals("Idle")){
				if(connect == 2){
					try{
						SYNC.send_string("IDLE\n");
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			} else if(arg.equals("Reboot")){
				if(connect == 2){
					try{
						status.append("Rebooting LPC\n");
						SYNC.send_string("QUIT\n");
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			} else if(arg.equals("Clear")){
				if(connect == 2){
					status.setText("");
				}
			} else if(arg.equals("Upload")){
				if(connect == 2){
					try{
						io_monitor.wait_for_reply = 1;
						SYNC.send_string("PUT\n");
						while(io_monitor.wait_for_reply == 1){};
						io_monitor.wait_for_reply = 1;
						SYNC.send_string(put_text.getText()+"\n");
						//SYNC.send_string("\n");
						while(io_monitor.wait_for_reply == 1){};
						SYNC.send_string("DONE\n");
					} catch (Exception f) {
						status.append("Problems sending request string\n");
					}
				}
			}
			return true;
		}
		return false;
	}
	
	
 	class Communications extends Thread{
		String	in_string;
		int		done = 0;
		int		i = -1, j=0, k;
		int		wait_for_reply = 0;
		int		delay;

		public void run(){
			while(done == 0){
				// i++; if(i > 10000) {i = 0; j++;};
				// k = j%100; if(k == 0) System.out.println("Tick: "+j);

				if(connect == 0){
					// do nothing
				} else {
					in_string = SYNC.get_string();
					if(in_string != null){
						delay = 0;
						// System.out.println(in_string);
						status.append(in_string);
						if(in_string.regionMatches(0, "ERROR", 0, 5) == true){
							wait_for_reply = 2;
						} else {
							wait_for_reply = 0;
						}
					}
					if(delay >= 300){
						delay = 0;
						connect = 0;
						SYNC.disconnect(SYNC.READ);
						SYNC.disconnect(SYNC.WRITE);
						status.append("Idle too long - disconnected\n");
					} else {
						delay++;
					}
				}
				try{sleep(200);} catch(Exception e){};
			}
		}

		public void destroy (){
			// INNER.endsocket();
    			try{
 		} catch (Exception p){
			};
		}
	}
}


