// bergmark - spring 1999 - ITX project

import java.io.*;
import cnrg.itx.*;
import cnrg.itx.signal.*;
import cnrg.itx.ds.*;

public class AddNewUser extends AbstractSignalingObserver {
	private DesktopSignaling myDS = null;
	private BufferedReader input= null;  


	// Default constructor
	public AddNewUser () {
		// Get a signaling object
		try {
			myDS = new DesktopSignaling ( this, "adm", "itxds" );
		} catch ( Exception e ) {
			System.out.println ("Couldn't authenticate because" + e.toString() );
			System.exit(0);
		}
		System.out.println ("Got a DesktopSignling!");
	}

	// This method reads a password in from stdin and sets it in
	// the directory. (Currently not supported)
	private void change ( UserID myID ) {
		char response;    
		System.out.println ("Entry exists: user = " + myID.toString());
		System.out.println ("Update pin for this user (y/n) ?");
		try {
			response = (char) input.read ();
			if ( response == 'y' ) {
				System.out.println ("Enter current password:");
				String oldPasswd = input.readLine();           
				System.out.println ("Enter new password:");  
				String passwd = input.readLine();           
				myDS.getDirectory().setPIN(myID, new Password (oldPasswd), 
										   new Password ( passwd ));   
			}      
		} catch ( Exception e ) {
			System.out.println ("Could not set new password because " +
								e.toString() );
		}
	}

	// This method solicits infomation for a new user and adds 
	// him or her to the database
	private void newUser ( ) {
		Digits extension = null;
		String user=null;
		Password pass=null;
		UserID myID=null;

		try {
			input = new BufferedReader (new InputStreamReader (System.in));
		} catch (Exception e ) {
			System.out.println ("Could not open input file");
		}

		System.out.println ("Enter userid x@cornell.edu:");
		try {
			user = input.readLine();
			myID = new UserID (user);   
		} catch ( Exception e) {
			System.out.println ( "Failed to make a new UserID because " + e.toString() );
			fini();
		}
		System.out.println ("Enter string to be used as a password:");
		try {
			pass = new Password ( input.readLine() );
		} catch ( Exception e ) {
			System.out.println ( "Failed to make a new password because " + e.toString() );
			fini();
		}
		try {
			extension = myDS.getDirectory().addUser (myID, 5, pass, DirectoryService.USER_ACCESS_LEVEL, "demo account" );
			System.out.println ("\n\nNew user added at Extension " + extension.toString() );
		} catch ( Exception e ) {
			System.out.println ( "Failed to create new directory entry because "  + e.toString() );
		}
	}

	// This method logs us out
	private void fini () {
		myDS.logout();
	}

	// Main program
	public static void main (String[] args) {
		AddNewUser me = new AddNewUser ();
		me.newUser();
		me.fini();            
	}
}
