package org.gcube.accounting.datamodel.validations.validators;

import java.util.regex.Matcher;

import org.gcube.com.fasterxml.jackson.annotation.JsonSetter;
import org.gcube.documentstore.exception.InvalidValueException;
import org.gcube.documentstore.records.DSMapper;

public class MatcherReplace {

	protected MultiMatcher multiMatcher;
	protected Replace replacementRegex;
	
	public MatcherReplace() {}
	
	public MultiMatcher getMultiMatcher() {
		return multiMatcher;
	}

	@JsonSetter(value="match")
	public void setMultiMatcher(MultiMatcher multiMatcher) {
		this.multiMatcher = multiMatcher;
	}

	protected Replace getReplacementRegex() {
		return replacementRegex;
	}

	@JsonSetter(value="replace")
	public void setReplacementRegex(Replace replacementRegex) {
		this.replacementRegex = replacementRegex;
	}

	public Replace check(String serviceClass, String serviceName, String calledMethod) throws InvalidValueException {
		boolean matched = multiMatcher.match(serviceClass, serviceName, calledMethod);
		Replace replace;
		if(matched) {
			replace = new Replace();
			
			Matcher serviceClassMatcher = multiMatcher.getServiceClassPattern().matcher(serviceClass);
			String replacementServiceClass = replacementRegex.getServiceClass();
			String replaceServiceClass = serviceClassMatcher.replaceFirst(replacementServiceClass);
			replace.setServiceClass(replaceServiceClass);
			
			Matcher serviceNameMatcher = multiMatcher.getServiceNamePattern().matcher(serviceName);
			String replacementServiceName = replacementRegex.getServiceName();
			String replaceServiceName = serviceNameMatcher.replaceFirst(replacementServiceName);
			replace.setServiceName(replaceServiceName);
			
			Matcher calledMethodMatcher = multiMatcher.getCalledMethodPattern().matcher(calledMethod);
			String replacementCalledMethod = replacementRegex.getCalledMethod();
			String replaceCalledMethod = calledMethodMatcher.replaceFirst(replacementCalledMethod);
			replace.setCalledMethod(replaceCalledMethod);
			
		}else {
			replace = null;
		}
		return replace;
	}

	@Override
	public String toString() {
		try {
			return DSMapper.getObjectMapper().writeValueAsString(this);
		} catch(Exception e) {
			return "MatcherReplace [multiMatcher=" + multiMatcher + ", replacer=" + replacementRegex + "]";
		}
	}
	
}
