/* ************************************************************************
#
#  DivConq
#
#  http://divconq.com/
#
#  Copyright:
#    Copyright 2012 eTimeline, LLC. All rights reserved.
#
#  License:
#    See the license.txt file in the project's top-level directory for details.
#
#  Authors:
#    * Andy White
#
************************************************************************ */
package divconq.test;

import java.io.FileInputStream;
import java.util.Scanner;
import java.util.concurrent.Semaphore;

import divconq.lang.HubResources;
import divconq.lang.OperationResult;
import divconq.log.DebugLevel;
import divconq.log.Logger;
import divconq.script.Activity;
import divconq.script.ActivityManager;
import divconq.script.ExecuteState;
import divconq.script.IInstructionCallback;
import divconq.struct.builder.JsonStreamBuilder;
import divconq.xml.XElement;
import divconq.xml.XmlReader;

public class TestScript {
	public static void main(String[] args) {
		try {
			HubResources resources = new HubResources("00101", true);
			resources.setDebugLevel(DebugLevel.Warn);
			OperationResult or = resources.init();
			
			if (or.hasErrors()) {
				Logger.error("Unable to continue, hub resources not properly initialized");
				return;
			}
			
			ActivityManager man = new ActivityManager();
			man.setSchema(resources.getSchema());
			
			// TODO init man
			
			XElement script = XmlReader.parse(new FileInputStream("../docs/dcl/99bottles.dcs.xml"));

			Activity act = new Activity(man);
			OperationResult compilelog = act.compile(script);
			
			if (compilelog.hasErrors()) {
				System.out.println("Errors: " + compilelog);
				return;
			}
			
			Scanner scn = new Scanner(System.in);
			
			System.out.println("Type 'debug' to step through program.");
			
			String op = scn.nextLine();
			
			if (!"debug".equals(op)) {
				act.resumeSimple();
				System.out.println("Script done. #" + act.getRuntime());
				return;
			}
			
			final Semaphore s = new Semaphore(0);
			
			final IInstructionCallback cb = new IInstructionCallback() {
				@Override
				public void resume() {
					s.release();
				}
			};
			
			while (act.getState() != ExecuteState.Exit) {
				act.runSingleInstruction(cb);
				
				s.acquire();
				
				System.out.println("------------------------------");
	    		
				act.getDebugInfo().toBuilder(new JsonStreamBuilder(System.out, true));	
				
				System.out.println("------------------------------");
				System.out.println("Press enter to continue.");
				
				scn.nextLine();
			}
			
			System.out.println("Script done.");
		} 
		catch (Exception x) {
			System.out.println("Error in loop: " + x);
		}
	}
}
