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.OdfTab;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.xpath.XPath;

public class CeltxTitlePage {

    CeltxConverter converter;
    OdfFileDom outputDom;
    Element officeText;

    public CeltxTitlePage(CeltxConverter converter) {
        this.converter = converter;
        this.outputDom = converter.getOutputDom();
        this.officeText = converter.getOfficeText();
    }

    void insertTitlePage() throws Exception {
        XPath htmlXPath = converter.getHtmlXPath();
        Document htmlDocument = converter.getHtmlDocument();

        String title = htmlXPath.evaluate("/html/head/title",
            htmlDocument);
        String author =
            htmlXPath.evaluate("/html/head/meta[@name='Author']/@content",
            htmlDocument);
        String contact =
            htmlXPath.evaluate("/html/head/meta[@name='CX.contact']/@content",
            htmlDocument);
        String byLine =
            htmlXPath.evaluate("/html/head/meta[@name='CX.byline']/@content",
            htmlDocument);
        String copyright =
            htmlXPath.evaluate("/html/head/meta[@name='DC.rights']/@content",
            htmlDocument);
        String basedOn =
            htmlXPath.evaluate("/html/head/meta[@name='DC.source']/@content",
            htmlDocument);
        OdfHeadingExtra p;
        int i;

		this.outputDom = (OdfFileDom) officeText.getOwnerDocument();

        p = new OdfHeadingExtra(outputDom, "CxFirstPage");
        officeText.appendChild(p);

        blankLines(10);

        p = new OdfHeadingExtra(outputDom, title, "CxTextCenter");
        officeText.appendChild(p);

        blankLines(2);

        p = new OdfHeadingExtra(outputDom, byLine, "CxTextCenter");
        officeText.appendChild(p);

        blankLines(2);

        p = new OdfHeadingExtra(outputDom, author, "CxTextCenter");
        officeText.appendChild(p);

        blankLines(2);

        p = new OdfHeadingExtra(outputDom, basedOn, "CxTextCenter");
        officeText.appendChild(p);

        blankLines(4);

        p = new OdfHeadingExtra(outputDom, copyright, "CxTitleTabs");
		p.appendChild(new OdfTab(outputDom));
		p.addContent(contact);
        officeText.appendChild(p);
    }

    void blankLines(int n) {
        for (int i = 0; i < n; i++) {
            OdfHeadingExtra p = new OdfHeadingExtra(outputDom);
            officeText.appendChild(p);
        }
	}
}
