package org.jerrymouse.gaes.mavenPlugin.eclipse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.plexus.util.IOUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;

public class EclipseConfig {
	File file;

	public EclipseConfig(File file) {
		this.file = file;
	}

	public void config() {
		try {
			Document document = new SAXReader().read(new FileReader(file));
			String s = config(document);
			IOUtil.copy(s, new FileOutputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public String config(Document document) {
		Element root = (Element) document.getRootElement().elements().get(0);
		List<String> wbResources = buildWRs();
		for (Object et : root.elements()) {
			Element e = (Element) et;
			if (e.getName().equalsIgnoreCase("wb-resource")) {
				if (e.attributeValue("deploy-path").equals("/")) {
					e.addAttribute("source-path", "war");
				}
				if (e.attributeValue("deploy-path").equals("/WEB-INF/classes")) {
					wbResources.remove(e.attributeValue("source-path"));
				}
			}
		}
		for (String string : wbResources) {
			Element element = root.addElement("wb-resource");
			element.addAttribute("deploy-path", "/WEB-INF/classes");
			element.addAttribute("source-path", string);
		}
		return document.asXML();
	}

	private List<String> buildWRs() {
		List<String> l = new ArrayList<String>();
//		l.add("src/main/java");
//		l.add("src/main/resources");
//		l.add("src/test/java");
//		l.add("src/test/resources");
		return l;
	}
}

