package org.jerrymouse.gaes.mavenPlugin.archetype;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.model.Parent;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class PatchReader {
	Log log = LogFactory.getLog(getClass());

	Patch read(Reader reader) {
		Patch patch = new Patch();
		Document document = creatDom(reader);
		patch.addParent = parseAddParent(document
				.selectSingleNode("/patch/addParent/parent"));
		patch.removeDistributionManagement = patchRemoveDistributionManagement(document
				.selectSingleNode("/patch/removeDistributionManagement"));
		return patch;
	}

	private boolean patchRemoveDistributionManagement(Node selectSingleNode) {
		if (selectSingleNode == null)
			return false;
		return new Boolean(selectSingleNode.getText().trim());
	}

	private Parent parseAddParent(Node node) {
		if (node == null)
			return null;
		log.trace(node.asXML());
		log.trace(node.getPath());

		Parent parent = new Parent();
		Node groupId = node.selectSingleNode(node.getPath() + "/groupId");
		Node artifactId = node.selectSingleNode(node.getPath() + "/artifactId");
		Node version = node.selectSingleNode(node.getPath() + "/version");
		Node relativePath = node.selectSingleNode(node.getPath()
				+ "/relativePath");
		Node modelEncoding = node.selectSingleNode(node.getPath()
				+ "/modelEncoding");
		parent.setGroupId(groupId.getText());
		parent.setArtifactId(artifactId.getText());
		if (version != null)
			parent.setVersion(version.getText());

		if (relativePath != null)
			parent.setRelativePath(relativePath.getText());
		if (modelEncoding != null) {
		}
		// parent.setModelEncoding(modelEncoding.getText());
		return parent;
	}

	private Document creatDom(Reader reader) {
		Document document = null;
		try {
			document = new SAXReader().read(reader);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		log.trace(document.asXML());
		return document;
	}

	public Patch read(InputStream in) {
		return read(new InputStreamReader(in));
	}
}
