package com.langintro.celtx_to_odt;

import org.openoffice.odf.doc.OdfFileDom;
import org.openoffice.odf.doc.element.text.OdfHeadingExtra;
import org.openoffice.odf.doc.element.text.OdfParagraphExtra;
import org.openoffice.odf.doc.element.text.OdfSpan;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.util.Properties;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;

public class CeltxCastOfCharacters {

    CeltxConverter converter;
    OdfFileDom outputDom;
    Element officeText;
	Properties translation;
	
    public CeltxCastOfCharacters(CeltxConverter converter) {
        this.converter = converter;
        this.outputDom = converter.getOutputDom();
        this.officeText = converter.getOfficeText();
		this.translation = converter.getTranslation();
    }

    void outputCastOfCharacters() throws Exception {
        XPath rdfXPath = converter.getRdfXPath();
        Document rdfDocument = converter.getRdfDocument();
		
        OdfParagraphExtra p;
		OdfHeadingExtra h;
		OdfSpan span;
		NodeList castMembers;
		Element castMember;
		String attributeValue;
		String legend;
		boolean hasNs1Namespace;

        int i;

		hasNs1Namespace = !(converter.getCeltxNamespaceContext().
			getNs1NamespaceUri().isEmpty());

        h = new OdfHeadingExtra(outputDom, 
			translation.getProperty("CHARACTER_HEADING"), "CxNewPageHeading");
        officeText.appendChild(h);

		castMembers = (NodeList) rdfXPath.evaluate("/RDF:RDF/cx:Cast",
			rdfDocument, XPathConstants.NODESET);

		for (i = 0; i < castMembers.getLength(); i++)
		{
			castMember = (Element) castMembers.item(i);
			attributeValue = rdfXPath.evaluate("@dc:title", castMember);
			h = new OdfHeadingExtra(outputDom,
				attributeValue, "Heading_20_2");
			officeText.appendChild(h);

			for (CharacterFields.CharacterFieldEntry cfe :
				CharacterFields.CharacterFieldEntry.values()) {
				if (!cfe.attrName.startsWith("NS1") || hasNs1Namespace)
				{
					attributeValue = (String) rdfXPath.evaluate("@" + cfe.attrName,
						castMember, XPathConstants.STRING);
					if (attributeValue != null && !attributeValue.isEmpty())
					{
						legend = translation.getProperty(cfe.translationIndex);
						p = new OdfParagraphExtra(outputDom, "Default");
						span = new OdfSpan(outputDom);
						span.setStyleName("CxBold");
						span.appendChild(outputDom.createTextNode(legend + ": "));
						p.appendChild(span);
						p.addContent(attributeValue);
						officeText.appendChild(p);
					}
				}
			}
		}
    }

}
