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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import be.jeffcheasey88.peeratcode.parser.java.CleanerPool;
import be.jeffcheasey88.peeratcode.parser.java.JavaElement;
import be.jeffcheasey88.peeratcode.parser.java.CleanerPool.Cleaner;

//ContainerOperation
public class IfOperation extends OperationContainer{
	
	private static Pattern PATTERN = Pattern.compile("^(\\s*if\\s*(\\^GENERIC_PARENTHESIS\\d+)).*$");
	
	private String condition; //replace by Operation
	
	public IfOperation(){}

	@Override
	public int parse(String content, CleanerPool cleaner) throws Exception{
		System.out.println("IF STATEMENT");
		CleanerPool generic = new CleanerPool(
				new Cleaner("GENERIC_PARENTHESIS",'(',')'),
				new Cleaner("GENERIC_FUNCTION", '{','}'));
		content = generic.clean(content);
		System.out.println("after clean "+content);
		
		Matcher matcher = PATTERN.matcher(content);
		matcher.matches();
		
		this.condition = generic.unzip(matcher.group(2), (s,p) -> s);
		
		int index = generic.unzip(matcher.group(1), (s,p) -> s).length();
		content = generic.unzip(content, (s,p) -> s).substring(index);
		System.out.println("INSIDE "+content);
		int bodysize;
		if(content.startsWith("{")){
			bodysize = content.indexOf('}')+1;
			content = content.substring(1, bodysize-1);
			parse(content, cleaner, generic);
		}else{
			bodysize = parseOne(content, cleaner, generic);
		}
		
		return index+bodysize;
	}

	@Override
	public void show(int tab) {
		String start = "";
		for(int i = 0; i < tab; i++) start+="\t";
		System.out.println(start+"if("+condition+"){");
		for(JavaElement child : getChilds()) child.show(tab+1);
		System.out.println(start+"}");
	}

}
