package be.jeffcheasey88.peeratcode.parser.java.operations;

import java.util.ArrayList;
import java.util.List;

import be.jeffcheasey88.peeratcode.parser.java.CleanerPool;
import be.jeffcheasey88.peeratcode.parser.java.JavaElement;
import be.jeffcheasey88.peeratcode.parser.java.Variable;
import be.jeffcheasey88.peeratcode.parser.java.Variable.MultipleDeclaratedVariable;

public abstract class OperationContainer extends JavaElement{
	
	private static OperationFactory FACTORY = OperationFactory.getFactory();
	
	private List<JavaElement> childs;

	public OperationContainer(){
		this.childs = new ArrayList<>();
	}
	
	public void parse(String content, CleanerPool global, CleanerPool local) throws Exception{
		content = local.unzip(content, (s,p) -> s);
		System.out.println("CONTAINER "+content);
		while(!(content.replaceAll("\\s+", "").isEmpty())) content = internalParse(content, global, local);
	}
	
	public int parseOne(String content, CleanerPool global, CleanerPool local) throws Exception{
		content = local.unzip(content, (s,p) -> s);
		String modify = internalParse(content, global, local);
		return content.length()-modify.length();
	}
	
	private String internalParse(String content, CleanerPool global, CleanerPool local) throws Exception{
		System.out.println("BODY "+content);
		
		JavaElement operation = FACTORY.buildOperation(content);
		
		System.out.println("got "+operation.getClass().getSimpleName());
		int index = operation.parse(content, local);
		content = content.substring(index);
		if(operation instanceof Variable){
			if(content.startsWith(",")){
				Variable variable = (Variable)operation;
				MultipleDeclaratedVariable multiple = new MultipleDeclaratedVariable(variable.getModifier(), variable.getType());
				multiple.addVariable(variable.getName(), variable.getValue());
				
				operation = multiple;
				
				boolean quote;
				do{
					variable = new Variable(variable.getModifier(), variable.getType());
					index = variable.parse(content, local);
					multiple.addVariable(variable.getName(), variable.getValue());
					content = content.substring(index);
					quote = content.startsWith(",");
					content = content.substring(1);
				}while(quote);
			}else content = content.substring(1);
		}
		
		this.childs.add(operation);
		return content;
	}
	
	public List<JavaElement> getChilds(){
		return this.childs;
	}
}
