package background.expressions;

import java.util.ArrayList;

import background.VariableManager;
import background.systemVariables.SimpleVariable;

public class StringProcess {
	
	public ArrayList<String> parts;
	public VariableManager variableManager;

	
	
	public StringProcess(String s, VariableManager vm) {
		variableManager = vm;

		processString(s);
	}
	
	public void processString(String s) {		
		parts = new ArrayList<String>();
		char c;
		String text = "";
		String variable = "";
		int counter = 0;
		
		for (int i=0; i<s.length(); i++) {
			c = s.charAt(i);
			
			if ((counter==0) && (c=='\"')) {
				text += c;
				counter++;
			} else if ((counter!=0) && (c=='\"')) {
				text += c;
				counter--;				
			} else if (counter!=0) {
				text += c;
			} else if (c=='.') {
				if (!text.isEmpty()) {
					parts.add(text.trim());
					text = ""; 
					variable = "";
				} else if (!variable.isEmpty()) {
					parts.add(variable.trim());
					variable = "";
				}
			} else {
				variable += c;
			}
			
		}
		if (!variable.trim().isEmpty()) parts.add(variable.trim());
		if (!text.trim().isEmpty()) parts.add(text.trim());		
	}
	

	public String getStringValue() {
		String result = "";
		for (String part: parts) {	
			if (part.startsWith("\"") && part.endsWith("\"")) {								// v uvodzovkach je priamo string
				result += part.substring(1, part.length()-1);
			} else {																		// bez uvodzoviek je nazov premennej stringoveho typu
				SimpleVariable sim = variableManager.getVariableByName(part);
				if (!sim.initialized) {
					variableManager.errorHandler.errorHappened("Initialized");
				} else result += sim.getValue(" ");
			}
		}
		return result;
	}

			
	public static Boolean hasOperator(String s) {		
		String[] st = {"\"", "."};
		
		for (int i=0; i<st.length; i++) {
			if (s.contains(st[i])) return true;
		}
		return false;
	}

}
