package hu.swankey.ammo.common.script.statements;

import hu.swankey.ammo.common.script.AmmoScriptException;
import hu.swankey.ammo.common.script.yunits.YAttribute;
import hu.swankey.ammo.common.yggdrasil.basics.YObject;

import java.util.Map;

public class Switch extends Statement {
    
    private final Map<Expression, Statement> cases;
    private final Block defaultCase;
    private final Expression switcherExpr;

    public Switch(Expression switcher, Map<Expression, Statement> cases, Block defaultCase){
    	
    	if (switcher == null)
    		throw new NullPointerException("'switcher' cannot be null");
    	
    	if (cases == null)
    		throw new NullPointerException("'cases' cannot be null");
    	
    	this.cases = cases;
    	this.switcherExpr = switcher;
    	this.defaultCase = defaultCase;
    }



	@Override
	public YObject evaulate(Map<String, YObject> envrionment, YObject thisElement) {
		YAttribute switcher = (YAttribute) switcherExpr.evaulate(envrionment, thisElement);
		
		Statement statement = null;
		
		for(Expression expr: cases.keySet())
			if (  ((YAttribute)expr.evaulate(envrionment, thisElement)).getValue() == switcher.getValue())
				statement = cases.get(expr);
		
		if (statement == null ) {			
			if (defaultCase == null){
				String status = "\nSwitcher: " + switcher + "\n Cases:";
				for(Expression expr: cases.keySet())
					status += "\n - <" + expr + "> : " + cases.get(expr);
				throw new AmmoScriptException("Switch Exception. Status: " + status);
			}
			statement = defaultCase;
		}
		
		statement.evaulate(envrionment, thisElement);
		
		return null;
	}


//
//	@Override
//	public boolean isValid(Map<String, YObject> envrionment, YObject thisElement) {
//		
//		if ( !switcherExpr.isValid(envrionment, thisElement) )
//			return false;
//		
//		if ( defaultCase != null && !defaultCase.isValid(envrionment, thisElement))
//			return false;
//		
//		for (Expression expr: cases.keySet())
//			if ( !expr.isValid(envrionment, thisElement) || !cases.get(expr).isValid(envrionment, thisElement)  )
//				return false;
//			
//		return true;
//	}




}