package org.etsi.mts.tdl;

import org.eclipse.xtext.conversion.IValueConverter;
import org.eclipse.xtext.conversion.ValueConverter;
import org.eclipse.xtext.conversion.ValueConverterException;
import org.eclipse.xtext.conversion.impl.AbstractValueConverter;
import org.eclipse.xtext.nodemodel.INode;

public class TDLValueConverterService extends EString2XtextConverter {

	private IdentifierValueConverter identifierValueConverter;
	private QIdentifierValueConverter qidentifierValueConverter;

	@ValueConverter(rule = "org.etsi.mts.tdl.TDLtx.Identifier")
	public IValueConverter<String> Identifier() {
		if (this.identifierValueConverter == null)
			this.identifierValueConverter = new IdentifierValueConverter(this.ID());
		return this.identifierValueConverter;
	}

	@ValueConverter(rule = "Identifier")
	public IValueConverter<String> TDLtxIdentifier() {
		return this.Identifier();
	}

	@ValueConverter(rule = "org.etsi.mts.tdl.TDLtx.QIdentifier")
	public IValueConverter<String> QIdentifier() {
		if (this.qidentifierValueConverter == null)
			this.qidentifierValueConverter = new QIdentifierValueConverter(this.ID());
		return this.qidentifierValueConverter;
	}

	@ValueConverter(rule = "QIdentifier")
	public IValueConverter<String> TDLtxQIdentifier() {
		return this.QIdentifier();
	}

	@ValueConverter(rule = "org.etsi.mts.tdl.TDLtx.GRIdentifier")
	public IValueConverter<String> GRIdentifier() {
		return this.QIdentifier();
	}

	@ValueConverter(rule = "GRIdentifier")
	public IValueConverter<String> TDLtxGRIdentifier() {
		return this.GRIdentifier();
	}
}

class IdentifierValueConverter extends AbstractValueConverter<String> {
	private IValueConverter<String> idValueConverter;

	public IdentifierValueConverter(IValueConverter<String> iValueConverter) {
		this.idValueConverter = iValueConverter;
	}

	@Override
	public String toValue(String string, INode node) throws ValueConverterException {
		return this.idValueConverter.toValue(string, node);
	}

	@Override
	public String toString(String value) throws ValueConverterException {
		return this.idValueConverter.toString(value);
	}

}

class QIdentifierValueConverter extends IdentifierValueConverter {

	public QIdentifierValueConverter(IValueConverter<String> iValueConverter) {
		super(iValueConverter);
	}

	@Override
	public String toValue(String string, INode node) throws ValueConverterException {
		String[] parts = string.split("\\.");
		for (int i = 0; i < parts.length; i++) {
			parts[i] = super.toValue(parts[i], node);
		}
		return String.join(".", parts);
	}

	@Override
	public String toString(String value) throws ValueConverterException {
		String[] parts = value.split("\\.");
		for (int i = 0; i < parts.length; i++) {
			parts[i] = super.toString(parts[i]);
		}
		return String.join(".", parts);
	}
}