package nl.nikhef.sfp.ddmi;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;

public abstract class DDMIElement {

	private String _label;
	private String _id;
	private String _condition;
	private String _name;
	private DDMIElement _parent;
	
	private String _sourceId;


	public void setSourceId(String id)
	{
		_sourceId = id;
	}
	
	
	public String getSourceId() 
	{
		if (_sourceId == null) {
			DDMIElement parent = getParent();
			if (!(parent instanceof DDMIGroup))
				return null;
			
			return DDMIGroup.class.cast(parent).getSourceId();
		}
		return _sourceId;
	}

	
	
	public void setLabel(String label) {
		_label = label;		
	}
	
	public String getLabel() {
		return _label;
	}
	
	/**
	 * @return the id
	 */
	public String getId() {
		return _id;
	}
	
	public void setName(String name) {
		_name = name;
	}
	
	public String getName() {
		if (_name == null && _label != null) {
			label2Name();
		}
		return _name;
	}

	private void label2Name() {
		
		StringBuilder sb = new StringBuilder();
		
		for (char c : _label.toCharArray())
		{
			if (c == '-' || c == ' ' || c == '/' || c == '.' || c == '(' || c == ')') {
				sb.append('_');
			} else if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')) 
			{				
				sb.append(c);
			} else if (c >='A' && c <='Z') {
				sb.append(Character.toLowerCase(c));
			}
		}
		System.out.println("Created name " + sb.toString());
		_name = sb.toString();
	}


	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		_id = id;
	}
	
	public void setParent(DDMIElement parent) 
	{
		_parent = parent;
	}
	
	public DDMIElement getParent() {
		return _parent;
	}
	
	
	
	

	public void setShowIf(String condition) 
	{
		_condition = condition;
	}
	
	public boolean isValid(DDMIContext ctx) {
		if (_parent != null) {
			if (!_parent.isValid(ctx)) return false;
		}
		
		if (ctx.getI2CLink() == null) return false;
		
		if (_condition == null) {
			return true;
		}

		Globals globals = ctx.getGlobals();
		
		LuaValue func = globals.load("return " + _condition);		
		LuaValue val =  func.call();
		boolean b=  val.checkboolean();
		return b;
	}
	
	public abstract void output(StringBuilder sb, DDMIContext ctx, int level);

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((_label == null) ? 0 : _label.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DDMIElement other = (DDMIElement) obj;
		if (_label == null) {
			if (other._label != null)
				return false;
		} else if (!_label.equals(other._label))
			return false;
		return true;
	}

}


