/*
 * Copyright
 *   2007 axYus - www.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.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.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.Loader;
import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
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 {
    private static final transient String DEFAULT_XML_ENCODING = "UTF-8";
    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.");
    }

    @Override
    public DataResultSetWrapperModel clone() {
        return this;
    }

    public DataResultSet getDataResultSet() {
        if(MySqlDataResultSet.class.getName().equals(className)) {
            try {
                MysqlDrsParser parser = new MysqlDrsParser();
                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();
            Charset cs = Charset.forName(DEFAULT_XML_ENCODING);
            OutputStreamWriter osw = new OutputStreamWriter(baos,cs);
            XmlOutputter out = new XmlOutputter(osw, cs.name());
            ((MySqlDataResultSet)drs).marshall(out);
            osw.flush();
            byteBuffer = baos.toByteArray();
            stringBuffer = new StringBuilder();
        } catch(Exception ex) {
            logger.error("setDataResultSet(DataResultSet)",ex);
        }
    }

}
