/**
 * JOnAS : Java(TM) OpenSource Application Server
 *
 * This library 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 2.1 of the License, or any later version.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial Developer : Guillaume Sauthier
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.generators.genbase.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.ow2.jonas.generators.genbase.GenBaseException;
import org.ow2.jonas.generators.genbase.archive.J2EEArchive;
import org.ow2.jonas.lib.util.I18n;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.lib.util.XMLSerializer;
import org.w3c.dom.Document;



import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * Store an Archive in compressed or uncompressed format
 *
 * @author Guillaume Sauthier
 */
public abstract class ArchiveStorer {

    /** Buffer Size */
    public static final int MAX_BUFFER_SIZE = 1024;

    /** i18n */
    private static I18n i18n = I18n.getInstance(ArchiveStorer.class);

    /** logger */
    private static Logger logger = Log.getLogger(Log.JONAS_GENBASE_PREFIX);

    /**
     * base J2EEArchive to be saved
     */
    private J2EEArchive archive;

    /**
     * already saved filenames
     */
    private List already;

    /** output filename */
    private String out = "";

    /**
     * Creates a new ArchiveStorer object.
     *
     * @param archive archive to be saved
     */
    public ArchiveStorer(J2EEArchive archive) {
        this.archive = archive;
        already = new Vector();
        // we must use Manifestof the J2EEArchive
        already.add(convertName("META-INF/MANIFEST.MF"));
    }

    /**
     * Fill an OutputStream with content from an InputStream
     *
     * @param is InputStream
     * @param os OutputStream
     *
     * @throws IOException When filling fails
     */
    protected static void fill(InputStream is, OutputStream os) throws IOException {
        byte[] buffer = new byte[MAX_BUFFER_SIZE];
        int read;

        while ((read = is.read(buffer, 0, MAX_BUFFER_SIZE)) != -1) {
            os.write(buffer, 0, read);
        }
        os.flush();
    }

    /**
     * add a file in saved archive
     *
     * @param name file name
     *
     * @throws IOException When save fails
     */
    protected abstract void addFile(String name) throws IOException;

    /**
     * convert a filename from unix to windows filename and reverse
     *
     * @param name name to be converted
     *
     * @return converted filename
     */
    protected abstract String convertName(String name);

    /**
     * Returns an OutputStream from the given name
     *
     * @param name the filename we want to open/create
     *
     * @return an OutputStream from the given name
     *
     * @throws IOException When OS cannot be created
     */
    protected abstract OutputStream getOutputStream(String name) throws IOException;

    /**
     * Store the content of the contained archive.
     *
     * @throws GenBaseException When cannot add all files
     */
    public void store() throws GenBaseException {

        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "Writing '" + out + "' ...");
        }

        for (Iterator i = archive.getContainedFiles().iterator(); i.hasNext();) {
            String name = (String) i.next();

            try {
                if (!archive.omit(convertName(name)) && !already.contains(convertName(name))) {

                    addFile(name);
                    already.add(convertName(name));
                }
            } catch (IOException ioe) {
                String err = i18n.getMessage("ArchiveStorer.store.addFile", name);
                throw new GenBaseException(err, ioe);
            }
        }

        // add Descriptors
        Map descs = archive.getDescriptors();

        for (Iterator i = descs.keySet().iterator(); i.hasNext();) {
            String name = (String) i.next();

            try {
                XMLSerializer ser = new XMLSerializer((Document) descs.get(name));
                OutputStream os = getOutputStream(name);
                ser.serialize(os);
                os.flush();
            } catch (IOException ioe) {
                String err = i18n.getMessage("ArchiveStorer.store.serialize", name);
                throw new GenBaseException(err, ioe);
            }
        }
    }
    /**
     * @return Returns the i18n.
     */
    public static I18n getI18n() {
        return i18n;
    }

    /**
     * @return Returns the archive.
     */
    public J2EEArchive getArchive() {
        return archive;
    }

    /**
     * @param out The out to set.
     */
    public void setOut(String out) {
        this.out = out;
    }
}