package divconq.template;

import java.util.Scanner;

import divconq.db.ObjectCallback;
import divconq.db.ObjectResult;
import divconq.db.QueryRequest;
import divconq.lang.Hub;
import divconq.lang.HubResources;
import divconq.lang.OperationResult;
import divconq.lang.TaskContext;
import divconq.log.Logger;
import divconq.test.TestDb;
import divconq.util.StringUtil;

public class Main {
	public static void main(String[] args) {
		// prepare resources for Hub start
		HubResources resources = new HubResources("00101", true);
		OperationResult or = resources.init();
		
		if (or.hasErrors()) {
			Logger.error("Unable to continue, hub resources not properly configured");
			return;
		}
	
		// start the hub
		Hub.instance.start(resources);
		
		// in prep for the console ui, use a new user context (for the new log id)
		TaskContext.useNewRoot();
		
		Scanner scan = new Scanner(System.in);
		boolean running = true;
		
		while(running) {
			try {
				System.out.println();
				System.out.println("-----------------------------------------------");
				System.out.println("   Test dcDb Connector Menu");
				System.out.println("-----------------------------------------------");
				System.out.println("0)  Exit");
				System.out.println("1)  Load stored proc results (testProc1)");

				String opt = scan.nextLine();
				
				Long mopt = StringUtil.parseInt(opt);
				
				if (mopt == null)
					continue;
				
				switch (mopt.intValue()) {
				case 0:
					running = false;
					break;
					
				case 1:
					// call the test procedure that is part of the dcTest package
					// so that package must be installed for this to work
					QueryRequest tp1 = new QueryRequest("testProc1", null);
					
					ObjectCallback callback = new ObjectCallback() {
						@Override
						public void process(ObjectResult res) {
							if (res.hasErrors()) {
								System.out.println(" Error:");
								TestDb.printPretty(res.getMessages());
							}
							else  {
								System.out.println(" Response:");
								TestDb.printPretty(res.getResult());
							}
						}
					};
					
					Hub.instance.getDatabase().submit(tp1, callback);
					
					break;					
				}
						
			}
			catch(Exception x) {
				System.out.println("CLI error: " + x);
			}
		}		
		
		Hub.instance.stop();
	}
}
