//
//  CSC 468. DBMS Organization
//

//  Stub for XpathPlus Code. Rename to class XathPlus if using.

//  Alex Dekhtyar.


import java.io.*;
import java.net.*;

public class ClientSide {

	/**
	 * @param args
	 */

// Stub for main client loop
// Note, only interactive mode is supported. You will need to write batch-processing
// code yourselves.

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
	Socket CSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        // use port 4444. if using another port, change the value.
        int port=4444;
        
        // Only localhost connections supported.
        // Try connecting to the MiniXBase server

        try {
            CSocket = new Socket("localhost", port);
            out = new PrintWriter(CSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(CSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: localhost.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to:" +
                               "localhost because ."+e.getMessage());
            System.exit(1);
        }

        // upon successful connection

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String query="";
        System.out.println("XPathPlus:");

        //  MAIN LOOP

        // read command, pass it without parsing to the MiniXBase server
        //  (only checks for the quit command)

        // Modify the part below to add processing.


        while ((fromServer = in.readLine()) != null) {
        	
        	//The data sent from the server is stored in 'fromServer' variable
        	//write any code here, if you want to format or do 
                //anything else with the result, before displaying it
        	
            System.out.println("Result: " + fromServer);
            if (fromServer.equals("exit"))
                break;
		    
            

            while(query.indexOf(";")==-1)
            {
              query = query+stdIn.readLine()+" ";
            }
            
            query=""+query.substring(0,query.indexOf(";"));
            
            if(query.equals("QUIT")||query.equals("quit") || 
               query.equals("QUIT ")|| query.equals("quit "))
            {
            	break; //breaks out of the main while loop 
            }
            
	    if (query != null) {
                System.out.println("MiniNXBase: " + query);
                out.println(query);
	    }
	    
	    query="";
        }//end of while

        out.close();
        in.close();
        stdIn.close();
        CSocket.close();
		

	}//end of main

}//end of class