/**
 * A server for networked databases.  This creates the database
 * (possibly asking it to load data from a file), creates a 
 * network server connection, gets administrator password and
 * runner password, and then sits there listening to the connection.
 *
 * $Id: DatabaseServer.java,v 1.3 1999/05/10 14:44:13 flynt Exp $
 *
 * Usage:
 *   % java DatabaseServer adminPassword runnerPassword
 * or
 *   % java DatabaseServer adminPassword runnerPassword IP Port
 * 
 * When a connection is made, it reads a password.  If the password
 * is correct, it opens the connection.  Otherwise, it terminates the
 * connection.
 *
 * When a request comes in, it unpacks it, determines the method of
 * the database to call, calls it, packs up the result, and sends
 * the result back to the caller.
 */
import java.net.*;
import java.io.*;
import ServerTransferObject;
import DatabaseFileIO;
import Database;
import DBProtocol;

public class DatabaseServer {
    ServerTransferObject sto;
    DBProtocol dbp;
    
    public DatabaseServer(String art, String artist, String bidder) {
	
	try {
	    dbp = new DBProtocol(art, artist, bidder);
	} catch (Exception e) {
	    System.out.println("Failed to create DBProtocol: " + 
			       e.getMessage());
	    System.exit(-1);
	}
	
	try {
	    sto = new ServerTransferObject();
	} catch (Exception e) {
	    System.out.println("Failed to create ServerTransferObject" +
			       e.getMessage());
	    System.exit(-1);
	}
    }
    
    public static void main(String[] args) 
        throws Exception // added by SamR
    {
	DatabaseServer dbs = null;
	try {
	    
	    dbs = new DatabaseServer(args[0], args[1], args[2]);
	    
	} catch (Exception e) {
	    System.out.println("Failed to initialize: " + e.getMessage());
	    throw e; // Added by SamR
	    // System.exit(-1);
	}
	
	String input = null;
	String reply = "testing\n";
	try {
	    input = dbs.sto.receive();
	} catch (Exception e) {
	    System.out.println("Failed receive: " + e.getMessage());
	}
	while (input.compareTo("QUIT") != 0) {
	    try {
		System.out.println("Input: .." + input + "..");
		reply = dbs.dbp.sort(input);
		dbs.sto.send(reply);
		//		System.out.println("Reply: " + reply);
	    } catch (Exception e) {
		System.out.println("Primary Loop failure: " + e.getMessage());
	    }
	    try {
		input = dbs.sto.receive();
	    } catch (Exception e) {
		System.out.println("Failed receive: " + e.getMessage());
	    }
		
	}
	
	try {
	    dbs.dbp.db.writeArtToFile("newArtFile");
	    dbs.dbp.db.writeArtistToFile("newArtistFile");
	    dbs.dbp.db.writeBidderToFile("newBidderFile");
	} catch (Exception e) {
	    System.out.println("Failed Writes: " + e.getMessage());
	}
	
    } // main(String[])
} // class DatabaseServer







