/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 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.dgfip.xemelios.web.navigate;

import fr.gouv.finances.dgfip.utils.IoUtils;
import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.common.DematTransform;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.web.AttributeHelper;
import fr.gouv.finances.dgfip.xemelios.web.utils.StdDispatchAction;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class ShowReferentiel extends StdDispatchAction {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ShowReferentiel.class);

    @Override
    protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        XemeliosUser user = AttributeHelper.getUser(request.getSession());

        String docId = request.getParameter("docId");
        String collectivite = request.getParameter("collectivite");
        try {
            DocumentModel dm = Loader.getDocumentsInfos(null).getDocumentById(docId);
            Pair coll = new Pair(collectivite, collectivite);
        	// TODO : fusion nomenclatures pour afficher le referentiel
            Vector<Document> vXmlData = DataLayerManager.getImplementation().getRepositorysAsDom(dm,coll,user);
            if(vXmlData.size()==0) {
                return mapping.findForward("noRef");
            }

			XPath xp = XPathFactory.newInstance().newXPath();
			xp.setNamespaceContext(new LocalNSCtx(dm.getNamespaces().getNamespaceURI("n")));

			Vector<Node> vRepository=new Vector<Node>();
			Node repository;
			for(Document docXml:vXmlData){
            	repository = (Node)xp.evaluate("//n:"+dm.getReferentiel(),docXml.getDocumentElement(),XPathConstants.NODE);
            	vRepository.add(repository);
			}
			Document docRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

			Element el = docRoot.createElementNS(vXmlData.get(0).getDocumentElement().getNamespaceURI(),vXmlData.get(0).getDocumentElement().getNodeName());
			docRoot.appendChild(el);
			//docRoot.appendChild(docRoot.adoptNode(vXmlData.get(0).getDocumentElement()));

			for(int i=0;i<vXmlData.get(0).getDocumentElement().getChildNodes().getLength();i++){
				Node current = vXmlData.get(0).getDocumentElement().getChildNodes().item(i);
				if(!current.getNodeName().equals("Nomenclatures") && Node.TEXT_NODE!=current.getNodeType()){
					docRoot.adoptNode(current);
					docRoot.getDocumentElement().appendChild(current);
				}
			}

			if (vRepository != null && vRepository.size() > 0) {
				for (int i = 0; i < vRepository.size(); i++) {
					Node nomencl = vRepository.get(i);
                    if(nomencl!=null) {
                        docRoot.adoptNode(nomencl);
                        docRoot.getDocumentElement().appendChild(nomencl);
                    }
				}
			}

            File f = new File(new File(dm.getBaseDirectory()),dm.getReferentielXsltFile());
            InputStream is = IoUtils.getInputStream(f.getPath());
            //InputStream htmlStream = DematTransform.transform(docRoot.getDocumentElement(),is,f.getParentFile().toURI().toURL().toExternalForm());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
            Transformer t = factory.newTransformer(new StreamSource(f));
            t.transform(new DOMSource(docRoot), new StreamResult(baos));
            OutputStream os = response.getOutputStream();
            os.write(baos.toByteArray());
            os.flush(); os.close();

        } catch(Exception ex) {
            logger.error("while displaying repository: ",ex);
        }


        return null;
    }

    private static class LocalNSCtx implements NamespaceContext {
    	private static String URI;

    	public LocalNSCtx(String uri){
    		URI=uri;
    	}

        public String getNamespaceURI(String prefix) {
            if("".equals(prefix)) return XMLConstants.NULL_NS_URI;
            else if("n".equals(prefix)) return URI;
            else if(XMLConstants.XML_NS_PREFIX.equals(prefix)) return XMLConstants.XML_NS_URI;
            else if(XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
            else return XMLConstants.NULL_NS_URI;
        }

        public String getPrefix(String namespaceURI) {
            if(URI.equals(namespaceURI)) return "n";
            else if(XMLConstants.XML_NS_URI.equals(namespaceURI)) return XMLConstants.XML_NS_PREFIX;
            else if(XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) return XMLConstants.XMLNS_ATTRIBUTE;
            else return XMLConstants.DEFAULT_NS_PREFIX;
        }

        public Iterator getPrefixes(String namespaceURI) {
            return new StringIterator(getPrefix(namespaceURI));
        }
    }
    private static class StringIterator<String> implements Iterator<String> {
        private String s;
        private boolean get = false;
        public StringIterator(String s) {
            super();
            this.s=s;
        }

        public boolean hasNext() {
            return !get;
        }

        public String next() {
            get = true;
            return s;
        }

        public void remove() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}
