/*
 * 
 * Copyright
 *  2009 axYus - www.axyus.com
 *  2009 Christophe 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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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.data.impl.mysql.serialization;

import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
import fr.gouv.finances.cp.xemelios.data.impl.mysql.MySqlDataResultSet;
import fr.gouv.finances.dgfip.utils.Base64;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsMapping;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsParser;
import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
import fr.gouv.finances.dgfip.xemelios.common.config.XPathModel;
import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import javax.xml.namespace.QName;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class DataResultSetWrapperModel implements XmlMarshallable {
    public static final Logger logger = Logger.getLogger(DataResultSetWrapperModel.class);
    public static final QName QN = new QName(DrswParser.DRSW_Namespace, "DataResultSetWrapper", "d");
    public static final QName ATTR_ClassName = new QName(DrswParser.DRSW_Namespace,"className", "d");

    private String className;
    private StringBuilder stringBuffer;
    private byte[] byteBuffer;

    public DataResultSetWrapperModel(QName tag) {
        super();
        stringBuffer = new StringBuilder();
    }

    public void addCharacterData(String cData) throws SAXException {
        stringBuffer.append(cData);
    }

    public void addChild(XmlMarshallable child, QName tag) throws SAXException {
        throw new SAXException("unexpected child: "+tag);
    }

    public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
        className = attributes.getValue(ATTR_ClassName.getNamespaceURI(), ATTR_ClassName.getLocalPart());
        return this;
    }

    public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
        return null;
    }

    public void marshall(XmlOutputter output) {
        output.startTag(QN);
        if(className==null) throw new RuntimeException("className must not be null !!!");
        output.addAttribute(ATTR_ClassName, className);
        if(byteBuffer!=null) {
            output.addCharacterData(Base64.encodeBytes(byteBuffer, true));
        } else {
            output.addCharacterData(stringBuffer.toString());
        }
        output.endTag(QN);
    }

    public void validate() throws InvalidXmlDefinition {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public QName getQName() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public DataResultSetWrapperModel clone() {
        return this;
    }

    public DataResultSet getDataResultSet() {
        if(MySqlDataResultSet.class.getName().equals(className)) {
            try {
                MysqlDrsParser parser = new MysqlDrsParser();
//                XmlMarshalParser parser = new XmlMarshalParser(new MyMapping(), true);
                if(byteBuffer==null) byteBuffer = Base64.decode(stringBuffer.toString());
                parser.parse(new ByteArrayInputStream(byteBuffer));
                XmlMarshallable obj = parser.getMarshallable();
                MySqlDataResultSet mdrs = (MySqlDataResultSet)obj;
                mdrs.finishInit(Loader.getDocumentsInfos(null));
                return mdrs;
            } catch(Exception ex) {
                logger.error("getDataResultSet()",ex);
                return null;
            }
        } else {
            throw new UnsupportedOperationException(className.concat(" is not yet supported as a serializable DataResultSet"));
        }
    }
    public void setDataResultSet(DataResultSet drs) {
        className = drs.getClass().getName();
        if(!(drs instanceof MySqlDataResultSet)) {
            throw new UnsupportedOperationException(drs.getClass().getName()+": not yet supported as a serializable DataResultSet");
        }
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(baos);
            XmlOutputter out = new XmlOutputter(osw, "UTF-8");
            ((MySqlDataResultSet)drs).marshall(out);
            osw.flush();
            byteBuffer = baos.toByteArray();
            stringBuffer = new StringBuilder();
        } catch(Exception ex) {
            logger.error("setDataResultSet(DataResultSet)",ex);
        }
    }

//    private class MyMapping extends DocumentsMapping {
//        public MyMapping() {
//            super();
//            put(MySqlDataResultSet.QN,MySqlDataResultSet.class);
//            put(new QName("xpath"),XPathModel.class);
//            put(new QName("from-clause"),XPathModel.class);
//            put(new QName("where-clause"),XPathModel.class);
//            put(new QName("select-clause"),XPathModel.class);
//            put(new QName("sql"),XPathModel.class);
//        }
//
//    }
}
