package com.kite9.k9server.command.xml.replace;

import com.kite9.k9server.adl.holder.ADL;
import com.kite9.k9server.command.CommandException;
import com.kite9.k9server.command.xml.AbstractADLCommand;

public abstract class AbstractReplaceCommand<E, T> extends AbstractADLCommand {

	public String fragmentId;
	public String from, to;
	
	protected abstract T getFromContent(ADL context);
	
	protected abstract T getToContent(ADL context);
	
	protected abstract E getExistingContent(ADL in);
	
	@Override
	public boolean applyCommand(ADL in) throws CommandException {
		checkProperties();
		E existing = getExistingContent(in);
		T fromContent = getFromContent(in);
		
		if (same(existing, fromContent)) {
			doReplace(in, existing, getToContent(in), fromContent);
			return true;
		} else {
			return false;
		}
	}

	protected void checkProperties() {
		ensureNotNull("fragmentId", fragmentId);
	}

	protected abstract void doReplace(ADL on, E site, T toContent, T fromContent);

	protected boolean same(E existing, T with) {
		return existing.equals(with);
	}

	@Override
	public boolean undoCommand(ADL in) throws CommandException {
		checkProperties();
		E existing = getExistingContent(in);
		T toContent = getToContent(in);

		if (same(existing, toContent)) {
			doReplace(in, existing, getFromContent(in), toContent);
			return true;
		} else {
			return false;
		}
	}
	
	
}
