/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2008 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.quittancement;

import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.importers.docetatProvider.AbstractWriter;
import fr.gouv.finances.dgfip.xemelios.importers.docetatProvider.AttributesHolder;
import fr.gouv.finances.dgfip.xemelios.importers.docetatProvider.NamespaceHolder;
import fr.gouv.finances.dgfip.xemelios.importers.docetatProvider.NodesHolder;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

/**
 *
 * @author chm
 */
public class QuittancementWriter extends AbstractWriter {
    private static final Logger logger = Logger.getLogger(QuittancementWriter.class);
    public static final transient String FACTURE_NS = "http://www.minefi.gouv.fr/cp/helios/pes_v2/facture";
    
    private boolean inNomenclature = false;
    private boolean writtingNomenclature = false;
    private Element nomenclatures = null, currentElement = null;
    private Document doc = null;
    
    private boolean hasAlreadyWrittenHeader = false;
    
    public QuittancementWriter(DocumentModel dm,OutputStream out, String encoding, AttributesHolder attHolder, NodesHolder nodeHolder, NamespaceHolder ns) {
        super(dm,out,encoding,attHolder,nodeHolder,ns);
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        if(!hasAlreadyWrittenHeader) {
            hasAlreadyWrittenHeader=true;
            AttributesImpl attrs = new AttributesImpl();
            startElement(FACTURE_NS,"DOC_PES_Facture","DOC_PES_Facture",attrs);
        }
        if(writtingNomenclature) {
            super.startElement(uri, localName, qName, atts);
        } else {
            if("Nomenclatures".equals(localName)) {
                inNomenclature = true;
                try {
                    DocumentBuilderFactory domF = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = domF.newDocumentBuilder();
                    doc = db.newDocument();
                    nomenclatures = doc.createElement("Nomenclatures");
                    currentElement = nomenclatures;
                } catch(Exception ex) {
                    logger.error(null,ex);
                }
            } else {
                if(inNomenclature) {
                    try {
                        Element localNode = doc.createElement(localName);
                        for(int i=0;i<atts.getLength();i++) {
                            String attName = atts.getLocalName(i);
                            Attr att = doc.createAttribute(attName==null ? atts.getQName(i) : attName);
                            att.setValue(atts.getValue(i));
                            localNode.setAttributeNode(att);
                        }
                        currentElement.appendChild(localNode);
                        currentElement = localNode;
                    } catch(Exception ex) {
                        logger.error("",ex);
                    }
                } else {
                    super.startElement(uri, localName, qName, atts);
                }
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(!writtingNomenclature) {
            if(inNomenclature) {
                if("Nomenclatures".equals(localName)) {
                    inNomenclature = false;
                } else {
                    currentElement = (Element)currentElement.getParentNode();
                }
            } else {
                super.endElement(uri, localName, qName);
                if("PESFacture".equals(localName)) {
                    // TODO: write nomenclature
                    if(nomenclatures!=null) {
                        writtingNomenclature = true;
                        writeNode(nomenclatures);
                        writtingNomenclature = false;
                    }
                }
            }
        } else {
            super.endElement(uri, localName, qName);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if(!inNomenclature && !writtingNomenclature)
            super.characters(ch, start, length);
    }
    

    @Override
    public void endDocument() throws SAXException {
        endElement(FACTURE_NS, "DOC_PES_Facture", "DOC_PES_Facture");
        super.endDocument();
    }
    
}
