package org.openoffice.odf.doc.element.text;

import org.openoffice.odf.doc.OdfFileDom;
import org.openoffice.odf.dom.OdfNamespace;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 *
 * @author J David Eisenberg
 */
public class OdfWhitespaceProcessor {
	private int nSpaces;
	private String partial;
	private OdfFileDom owner;
	private Element element;

	public void append(Element element, String content)
	{
		int i = 0;
		char previous;
		char ch;

		this.element = element;
		partial = "";
		nSpaces = 0;
		owner = (OdfFileDom) element.getOwnerDocument();

		for (i = 0; i < content.length(); i++)
		{
			ch = content.charAt(i);
			if (ch == ' ')
			{
				if (nSpaces == 0)
				{
					partial += " ";
				}
				nSpaces++;
			}
			else if (ch == '\n')
			{
				emitPartial();
				element.appendChild(new OdfLineBreak(owner));
			}
			else if (ch != '\r')	// ignore DOS half of CR-LF
			{
				partial += ch;
				nSpaces = 0;
			}
		}
		emitPartial();
	}

	/*
	 * Send out any information that has been buffered
	 */
	private void emitPartial()
	{
		/* send out any partial text */
		if (!partial.equals(""))
		{
			element.appendChild(owner.createTextNode(partial));
		}
		/* and any spaces if necessary */
		if (nSpaces > 1)
		{
			OdfSpace spaceElement = new OdfSpace(owner);
			spaceElement.setC(nSpaces - 1);
			element.appendChild(spaceElement);
		}
		/* and reset all the counters */
		nSpaces = 0;
		partial = "";
	}

	public String getText(Node element)
	{
		String result = "";
		int spaceCount;
		Node node = element.getFirstChild();
		while (node != null)
		{
			if (node.getNodeType() == Node.TEXT_NODE)
			{
				result += node.getNodeValue();
			}
			else if (node.getNodeType() == Node.ELEMENT_NODE)
			{
				if (node.getLocalName().equals("s")) // text:s
				{
					try
					{
						spaceCount = Integer.parseInt(
							((Element) node).getAttributeNS(
							OdfNamespace.TEXT.getUri(), "c"));
					}
					catch(Exception e)
					{
						spaceCount = 1;
					}
					for (int i = 0; i < spaceCount; i++)
					{
						result += " ";
					}
				}
				else if (node.getLocalName().equals("line-break"))
				{
					result += "\n";
				}
				else if (node.getLocalName().equals("tab-stop"))
				{
					result += "\t";
				}
				else
				{
					result = result + getText(node);
				}
			}
		}
		return result;
	}

	public static void appendText(Element element, String content)
	{
		OdfWhitespaceProcessor processor = new OdfWhitespaceProcessor();
		processor.append(element, content);
	}
}
