/**
 * Copyright 2009 - 2014 J&#246;rgen Lundgren
 * 
 * This file is part of org.cel4j.
 * 
 * org.cel4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * org.cel4j is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with org.cel4j. If not, see <http://www.gnu.org/licenses/>.
 */
package org.cel4j.eleonore.simple;

import static org.macroing.common.lang.Throwables.doAssertObjectIsNotNull;

import java.util.regex.Matcher;

import org.cel4j.eleonore.Interpreter;
import org.cel4j.eleonore.InterpreterContext;
import org.cel4j.eleonore.Symbol;

final class SimpleStringInterpreter implements Interpreter {
	private static final String REGEX_STRING = "string";
	private static final String REGEX_STRING_LITERAL = "\"(\\\\.|[^\\\\\"])*\"";//"\"((?=\\\\\")..|(?!\").)*\"";//"\"(\\\\.|[^\\\\\"])*\"";
	
	SimpleStringInterpreter() {
		
	}
	
	@Override
	public void interpret(InterpreterContext interpreterContext) throws NullPointerException {
		doAssertObjectIsNotNull(interpreterContext, "interpreterContext");
		doInterpret(interpreterContext);
	}
	
	private void doInterpret(InterpreterContext interpreterContext) {
		if(!interpreterContext.isAccepted(REGEX_STRING, true)) {
			interpreterContext.reject();
			
			return;
		}
		
		if(interpreterContext.isAccepted(".*", false)) {
			interpreterContext.accept();
			
			Symbol symbol = interpreterContext.pop();
			
			if(!symbol.matches(REGEX_STRING_LITERAL)) {
				String string = symbol.toString();
				string = string.replaceAll("(?<!\\\\)(?=\").", Matcher.quoteReplacement("\\\""));
				string = "\"" + string + "\"";
				
				symbol = Symbol.valueOf(string);
			}
			
			interpreterContext.push(symbol);
			interpreterContext.accept();
		} else {
			interpreterContext.reject();
		}
	}
}