package edu.fichte.pbi.ide.views;

import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;

import edu.fichte.pbi.util.CallbackVariableListener;
import edu.fichte.pbi.vm.IRunWatcher;
import edu.fichte.pbi.vm.Machine;
import edu.fichte.pbi.vm.var.IVariable;

public class VariableView extends ViewPart implements IRunWatcher {
	
	public static String ID = "edu.fichte.pbi.ide.variableView";
	
	private Machine machine;
	
	private Label[] varLabel = new Label[14];
	private Label[] varValue = new Label[14];

	@Override
	public void createPartControl(Composite parent) {
		Composite layoutParent = new Composite(parent, 0);
		layoutParent.setLayout(new GridLayout(2, false));
		
		for (int i = 0; i < varLabel.length; i++) {
			varLabel[i] = new Label(layoutParent, 0);
			varLabel[i].setText("B" + String.valueOf(i));
			varValue[i] = new Label(layoutParent, 0);
			varValue[i].setText("0");
		}
	}

	@Override
	public void setMachine(Machine machine) {
		this.machine = machine;

		IVariable[] listener = new IVariable[varLabel.length];
		for (int i = 0; i < varLabel.length; i++) {
			listener[i] = this.machine.parseIVariable("B" + String.valueOf(i));
			listener[i].setVariableListener(
					new CallbackVariableListener(varValue[i]) {
				
				@Override
				public void variableChanged(IVariable variable) {
					final long value = variable.getValue();
					getSite().getShell().getDisplay().syncExec(new Runnable() {
						@Override
						public void run() {
							((Label) callback).setText(String.valueOf(value));
							((Label) callback).pack();
						}
						
					});
				}
			});
		}
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
		
	}

}
