package com.avitech.xslextension;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FlightPlanHelper {

	private static final Logger log = Logger.getLogger(FlightPlanHelper.class
			.getName());
	static {
		try {
			log.addHandler(new FileHandler());
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getAddressContent(NodeList addressNodes) {
		log.info("called getAddressContent");
		String result;
		try {
			// logNodes(addressNodes);
			StringBuffer addresses = new StringBuffer();
			StringBuffer extraAddresses = new StringBuffer();
			Node doc = addressNodes.item(0);
			NodeList list = doc.getChildNodes();
			log.info("Elemente:" + String.valueOf(list));

			for (int i = 0; i < list.getLength(); i++) {
				final Node node = list.item(i);
				if ("Addresses".equals(node.getNodeName())) {
					if (addresses.length() > 0) {
						addresses.append(' ');
					}
					log.info(
							"Node type of child: "
									+ node.getFirstChild().getNodeType());
					addresses.append(node.getFirstChild().getNodeValue());
				} else if ("ExtraAddresses".equals(node.getNodeName())) {
					if (addresses.length() > 0) {
						addresses.append(' ');
					}
					extraAddresses.append("AD ");
					log.info(
							"Node type of child: "
									+ node.getFirstChild().getNodeType());
					extraAddresses.append(node.getFirstChild().getNodeValue());
				} else {
					addresses.append("Unkown Node: '" + node.getNodeName()
							+ "' ");
				}
			}
			result = addresses.append((addresses.length() > 0) ? " " : "")
					.append(extraAddresses.toString()).toString();
		} catch (NullPointerException e) {
			log.log(Level.SEVERE, e.getLocalizedMessage(), e);
			result = "";
		}
		log.info("Result = '" + result + "'");
		return result;
	}

	private static void logNodes(NodeList nodes) {
		for (int i = 0; i < nodes.getLength(); i++) {
			log.info("Child: " + i);
			Node node = nodes.item(i);
			log.info(
					"Opening type '" + node.getNodeType() + "' node "
							+ String.valueOf(node.getNodeName()));
			final NamedNodeMap attributes = node.getAttributes();
			if (node.getNodeType() == Node.ELEMENT_NODE && attributes != null) {
				log.info("Attributes: ");
				for (int a = 0; a < attributes.getLength(); a++) {
					Node attribute = attributes.item(a);
					log.info(
							"  " + attribute.getNodeName() + ":"
									+ attribute.getNodeValue());
				}
			}
			if (node.getChildNodes().getLength() > 0) {
				log.info("Children: ");
				logNodes(node.getChildNodes());
			}
			log.info("Closing node " + String.valueOf(node.getNodeName()));
		}
	}

	public static Document splitIntoLines(final String content,
			final NodeList lineElements) {
		Document result = new XmlDocument();
		Element docRoot = result.createElement("result");
		log.info("called splitIntoLines");
		int lineIndex = 0;
		int pointer = 0;
		try {
			Document doc = (Document) lineElements.item(0);
			NodeList lines = doc.getChildNodes();
			while (pointer < content.length() && lineIndex < lines.getLength()) {
				Node line = lines.item(lineIndex);
				int lineLength = Integer.parseInt(line.getAttributes()
						.getNamedItem("length").getNodeValue());
				log.info(
						"Line " + lineIndex + " has max length of "
								+ lineLength);
				// Wir entnehmen dem content einen Substring von maximal
				// lineLength
				// Zeichen
				String subString = content.substring(pointer, Math.min(content
						.length(), pointer + lineLength));
				String lineContent;
				// Falls der Ausschnitt mitten in einem Wort endet...
				if (subString.length() == lineLength
						&& !content.endsWith(subString)) {
					int lastSpacePointer = subString.lastIndexOf(' ');
					// falls kein Space in der Zeichenkette ist, wird nicht
					// umgebrochen, sonst wird an der Position des letzten Space
					// umgebrochen.
					if (lastSpacePointer == -1) {
						lastSpacePointer = lineLength;
					}
					lineContent = subString.substring(0, lastSpacePointer);
				} else {
					lineContent = subString;
				}
				log.info(
						"Line " + lineIndex + " will be filled with '"
								+ lineContent + "'");
				line = result.createElement("line");
				line.appendChild(result.createTextNode(lineContent));
				docRoot.appendChild(line);
				pointer += lineContent.length();
				lineIndex++;
			}
			if (pointer >= content.length()) {
				docRoot.appendChild(result.createElement("overflow"));
			}
		} catch (NumberFormatException e) {
			log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} catch (DOMException e) {
			log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}

		return result;
	}
}
