/**
 * 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 1any 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.jonasadmin.test.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;

import org.apache.tools.ant.BuildException;

/**
 * Class to use jonas files
 * @author kemlerp
 *
 */
public class JonasAdminFiles {

    /**
     * Get "server.xml" created files by the test
     * @return The table of created files
     */
    private static Vector getCreatedFiles(String beginTime, String endTime) {
        Vector createdFiles = new Vector();

        // Get JONAS_BASE path
        String jonasBase = System.getProperty("jonas.base");

        // Get JONAS_BASE/conf path
        String conf = jonasBase + File.separator + "conf";

        // Get JONAS_BASE/conf directory
        File directory = new File(conf);

        // Get JONAS_BASE conf files
        File[] files = directory.listFiles();

        // First name of file to compare
        String beginName = "server.xml." + beginTime;

        // End name of file to compare
        String endName = "server.xml." + endTime;

        // Get the created files by the test
        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().compareTo(beginName) >= 0) {
                if (files[i].getName().compareTo(endName) <= 0) {
                    createdFiles.add(files[i]);
                }
            }
        }
        return createdFiles;
    }

    /**
     * Delete files
     * @param beginTime begin time of the test
     * @param endTime end time of the test
     */
    public static void deleteCreatedFiles(String beginTime, String endTime) {
        Vector files = getCreatedFiles(beginTime, endTime);

        for (int i = 0; i < files.size(); i++) {
            // Delete file
            ((File) files.get(i)).delete();
        }
    }

    /**
     * Delete file in $JONAS_BASE/conf directory
     * @param fileName name of the file
     */
    public static void deleteConfigFile(String fileName) {

        // Get JONAS_BASE path
        String jonasBase = System.getProperty("jonas.base");

        // Get JONAS_BASE/conf/... path
        String serverConfPath = jonasBase + File.separator + "conf" + File.separator + fileName;

        // Get file
        File file = new File(serverConfPath);

        // delete file
        file.delete();
    }

    /**
     * Replace server.xml by previous configuration file and remove created files
     * @param beginTime begin time of the test
     * @param endTime end time of the test
     */
    public static void recoverServerConf(String beginTime, String endTime) {
        Vector files = getCreatedFiles(beginTime, endTime);

        if (files.size() > 0) {
            // Get server.xml file
            File serverConf = getServerXmlFile();
            // Get the older copied configuration file
            File copiedFile = (File) files.get(0);

            // Rename previous configuration file to "server.xml"
            if (serverConf.canWrite()) {
                copiedFile.renameTo(serverConf);
            }

            // Delete other created files
            for (int i = 0; i < files.size(); i++) {
                ((File) files.get(i)).delete();
            }
        }
    }


    /**
     * Get server.xml file
     * @return File server.xml
     */
    public static File getServerXmlFile() {
        // Get JONAS_BASE path
        String jonasBase = System.getProperty("jonas.base");

        // Get JONAS_BASE/conf/server.xml path
        String serverConfPath = jonasBase + File.separator + "conf" + File.separator + "server.xml";

        // Get server.xml file
        return new File(serverConfPath);
    }

    /**
     * Get previous server.xml file
     * @param beginTime begin time of the test
     * @param endTime end time of the test
     * @return File
     */
    public static File getPreviousServerXmlFile(String beginTime, String endTime) {
        Vector files = getCreatedFiles(beginTime, endTime);
        return (File) files.get(files.size() - 1);
    }

    /**
     * Get local joram server port
     * @param fileName name of the administration task file: joram-admin.cfg (in JONAS_BASE/conf directory)
     * @return port number
     * @throws IOException if an error occurs while file is read
     */
    public static String getJoramServerPort(String fileName) throws IOException {
        String port = null;

        // Get JONAS_BASE path
        String jonasBase = System.getProperty("jonas.base");

        // Get JONAS_BASE/conf/server.xml path
        String serverConfPath = jonasBase + File.separator + "conf" + File.separator + fileName;

        // Get server.xml file
        File file = new File(serverConfPath);

        // Transform file into string
        BufferedReader read = new BufferedReader(new FileReader(file));
        String line = read.readLine();
        while (line != null) {
            if (line.startsWith("Port")) {
                // Get port
                port = line.substring("Port\t".length());
            }
            line = read.readLine();
        }
        read.close();

        return port;
    }

    /**
     * Get local joram server host name
     * @param fileName name of the administration task file: joram-admin.cfg (in JONAS_BASE/conf directory)
     * @return host name
     * @throws IOException if an error occurs while file is read
     */
    public static String getJoramHostName(String fileName) throws IOException {
        String hostName = null;

        // Get JONAS_BASE path
        String jonasBase = System.getProperty("jonas.base");

        // Get JONAS_BASE/conf/server.xml path
        String serverConfPath = jonasBase + File.separator + "conf" + File.separator + fileName;

        // Get server.xml file
        File file = new File(serverConfPath);

        // Transform file into string
        BufferedReader read = new BufferedReader(new FileReader(file));
        String line = read.readLine();
        while (line != null) {
            if (line.startsWith("Host")) {
                // Get port
                hostName = line.substring("Host\t".length());
            }
            line = read.readLine();
        }
        read.close();

        return hostName;
    }

    public static void writeConfigFile(String fileName, Properties properties) throws IOException {

        // Get JONAS_BASE path
        String jonasBase = System.getProperty("jonas.base");

        // Get JONAS_BASE/conf/... path
        String serverConfPath = jonasBase + File.separator + "conf" + File.separator + fileName;

        // Get file
        File file = new File(serverConfPath);

        // Write the properties file back out
        FileOutputStream output = null;

        try {
            output = new FileOutputStream(file);

            final String header = "File was created by jonasAdmin test suite.";

            properties.store(output, header);
        } catch (final IOException ioe) {
            final String message = "Error while writing " + file;
            throw new BuildException(message, ioe);
        }

    }
}
