/* ************************************************************************
#
#  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.script.inst;

import divconq.script.ExecuteState;
import divconq.script.IInstructionCallback;
import divconq.script.StackEntry;
import divconq.struct.ScalarStruct;
import divconq.struct.Struct;

public class Var extends With {
	@Override
	public void run(final StackEntry stack, IInstructionCallback cb) {
		if (stack.getState() == ExecuteState.Ready) {
            String def = stack.stringFromSource("Type");
            String name = stack.stringFromSource("Name");
            
            Struct var = stack.getActivity().createStruct(def);
            
			if (var == null) {
				stack.setState(ExecuteState.Exit);
				stack.log().errorTr(520);
				cb.resume();
				return;
			}

			if (stack.codeHasAttribute("SetTo")) {
		        Struct var3 = stack.refFromSource("SetTo", var.getType());
	
				if (var3 == null) {
					stack.setState(ExecuteState.Exit);
					stack.log().errorTr(521);
					cb.resume();
					return;
				}
				
				if (var instanceof ScalarStruct) 
					((ScalarStruct) var).adaptValue(var3);
				else
					var = var3;
			}
			
            stack.addVariable(name, var);

			stack.getStore().setField("CurrNode", 0);
			stack.getStore().setField("Target", var);
			stack.setState(ExecuteState.Resume);
			
			cb.resume();
		}		
		else
			super.run(stack, cb);
	}
}
