/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * 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
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas_lib.deployment.work;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.objectweb.jonas.common.Log;

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

/**
 * JOnAS File manager.<br>
 * This class provides a way for managing the working package files.
 * @author Florent Benoit
 */

public class FileManager {

    /**
     * Format of a timestamp dir.
     */
    private static final String TIMESTAMP_FORMAT = "_yyyy.MM.dd-HH.mm.ss";

    /**
     * Size of the buffer.
     */
    private static final int BUFFER_SIZE = 2048;

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

    /**
     * Constructor. Private as it is an utility class
     */
    protected FileManager() {

    }

    /**
     * Give the unpack destination directory of the specified file.
     * @param urlFileName the url of the name of the EAR file (ends with the
     *        .ear extension).
     * @return the timestamp destination directory of the specified file.
     * @throws FileManagerException if we can't get the timestamp.
     */
    public static String fileToTimeStampDir(URL urlFileName) throws FileManagerException {
        return fileToTimeStampDir(urlFileName, "");
    }

    /**
     * Give the unpack destination directory of the specified file.
     * @param urlFileName the url of the name of the EAR file (ends with the
     *        .ear extension).
     * @param ext the suffix to concatenate to the build name
     * @return the timestamp destination directory of the specified file.
     * @throws FileManagerException if we can't get the timestamp.
     */
    public static String fileToTimeStampDir(URL urlFileName, String ext) throws FileManagerException {

        // check protocol
        if (!urlFileName.getProtocol().equalsIgnoreCase("file")) {
            throw new FileManagerException("Only the file:/ URL can be used");
        }

        File urlFile = null;
        urlFile = new File(urlFileName.getFile());

        if (!urlFile.exists()) {
            throw new FileManagerException("The file " + urlFileName.getFile() + " was not found.");
        }

        // Create a format
        SimpleDateFormat sdf = new SimpleDateFormat(TIMESTAMP_FORMAT);

        // get the date of the Ear file
        long lastModified = urlFile.lastModified();

        if (lastModified == 0L) {
            throw new FileManagerException("Can't read the last modified time for the file" + urlFile + ".");
        }

        // Date
        Date d = new Date(lastModified);

        // Return String
        String stReturn = urlFile.getName();
        // Remove extension .ear
        int lastIndex = stReturn.lastIndexOf(".");
        if (lastIndex == -1) {
            throw new FileManagerException("The specified file " + urlFileName.getFile()
                    + " is not a file with the format XXX.ear.");
        }

        stReturn = stReturn.substring(0, lastIndex);

        stReturn += sdf.format(d) + ext;

        return stReturn;
    }

    /**
     * Write an input stream to a given file.
     * @param in the inputStream.
     * @param earEntryFile the file where the inputstream must be dumped.
     * @throws FileManagerException if the dump failed.
     */
    protected static void dump(InputStream in, File earEntryFile) throws FileManagerException {

        try {
            // File output
            FileOutputStream out = new FileOutputStream(earEntryFile);
            int n = 0;
            try {
                // buffer
                byte[] buffer = new byte[BUFFER_SIZE];

                while ((n = in.read(buffer)) > 0) {
                    out.write(buffer, 0, n);
                }
            } finally {
                out.close();
            }
        } catch (IOException e) {
            String err = "Error while uncompressing the file " + earEntryFile;
            logger.log(BasicLevel.ERROR, err);
            throw new FileManagerException(err, e);
        }
    }

    }