/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 Bull S.A.S.
 * Contact: jonas-team@ow2.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.ow2.jonas.antmodular.jonasbase.bootstrap;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.ow2.jonas.antmodular.bootstrap.BootstrapTask;
import org.ow2.jonas.antmodular.bootstrap.JOnASAntTool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;

/**
 * Abstract jonas base task
 */
public abstract class AbstractJOnASBaseAntTask extends Task {

    /**
     * Source directory (JOnAS root).
     */
    protected File jonasRoot = null;

    /**
     * Destination directory (Where create the jonasBase).
     */
    protected File destDir = null;

    /**
     * List of tasks to execute
     */
    protected List tasks;

    /**
     * Configuration directory of JOnAS
     */
    protected static final String CONF_DIR = "/conf";

    /**
     * Allow to skip copy of optional deployables
     */
    protected boolean skipOptionalDeployablesCopy = false;

    /**
     * Default constructor
     */
    protected AbstractJOnASBaseAntTask() {
        this.tasks = new ArrayList();
    }

    /**
     * Run this task.
     * @see org.apache.tools.ant.Task#execute()
     */
    @Override
    public void execute() {
        this.jonasRoot = new File(getJOnASRoot());
        this.destDir = new File(getJOnASBase());

        if (this.jonasRoot == null) {
            throw new BuildException("jonasRoot element is not set");
        }

        if (this.destDir == null) {
            throw new BuildException("destDir element is not set");
        }

        if (this.jonasRoot.getPath().equals(this.destDir.getPath())) {
            throw new BuildException("jonasRoot and destDir is the same path !");
        }
    }

    /**
     * Execute all tasks
     */
    public void executeAllTask() {

        Iterator it = this.tasks.iterator();
        while (it.hasNext()) {
            Object o = it.next();

            if (o instanceof BaseTaskItf) {
                BaseTaskItf task = (BaseTaskItf) o;
                task.setDestDir(this.destDir);
                task.setJonasRoot(this.jonasRoot);
                if (task instanceof BootstrapTask) {
                    ((BootstrapTask) task).setJonasBase(this.destDir);
                }
                JOnASAntTool.configure(this, (Task) task);
                String info = task.getLogInfo();
                if (info != null) {
                    log(info, Project.MSG_INFO);
                }
                task.execute();
            } else {
                Task task = (Task) o;
                JOnASAntTool.configure(this, task);
                task.execute();
            }
        }
    }


    /**
     * Add tasks for configured object.
     * @param subTasks some tasks to do on files
     */
    public void addTasks(final Tasks subTasks) {
        if (subTasks != null) {
            for (Iterator it = subTasks.getTasks().iterator(); it.hasNext();) {
                tasks.add(it.next());
            }
        }
    }

    /**
     * Add a task for configure some objects.
     * @param task the task to do
     */
    public void addTask(final BaseTaskItf task) {
        if (task != null) {
            tasks.add(task);
        }
    }

    /**
     * Return Jms tasks
     * @return all tasks
     */
    public List getTasks() {
        return tasks;
    }

    /**
     * Create a JReplace Task for changing service classname in jonas.properties.
     *
     * @param serviceName service classname to use.
     * @return Returns a JReplace Task.
     */
    protected JTask createServiceNameReplace(final String serviceName, final String info, final String confDir, String property) {
        // Replace the service in jonas.properties file
        JTask jtask = new JTask();
        jtask.setDestDir(destDir);
        jtask.changeValueForKey(info, confDir, JOnASBaseTask.JONAS_CONF_FILE, property, serviceName, false);
        jtask.setLogInfo(info + "Setting service to : " + serviceName);
        return jtask;
    }

    /**
     * @param destDir Destination directory to set
     */
    public void setDestDir(File destDir) {
        this.destDir = destDir;
    }

    /**
     * @return the path of the JONAS_ROOT
     */
    public String getJOnASRoot() {
        return getProject().getProperty("jonas.root");
    }
    

    /**
     * @return the path of the JONAS_BASE
     */
    public String getJOnASBase() {
        return getProject().getProperty("jonas.base");  
    }

    /**
     * @param resourcePackage Resources package of template deployables to retrieve and to copy in the deploy directory
     *                        of the JOnAS instance
     */
    protected void copyTemplateDeployables(final String resourcePackage) {
        String templatePackage = resourcePackage.trim();
        if (!templatePackage.endsWith("/")) {
            templatePackage = templatePackage + "/";
        }

        //build the pattern
        final String resourcePattern = templatePackage + ".+";
        Pattern pattern = Pattern.compile(resourcePattern);

        //get access to the JAR file (if templates are presents
        URL url = getClass().getClassLoader().getResource("templates");
        String jarFileName = null;
        try {
            jarFileName = URLDecoder.decode(url.getFile(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new BuildException("Cannot build jar filename from url " + url, e);
        }
        jarFileName = jarFileName.substring(5,jarFileName.indexOf("!"));
        JarFile jarFile = null;
        try {
            jarFile = new JarFile(jarFileName);
        } catch (IOException e) {
            throw new BuildException("Cannot build jar file from url " + url, e);
        }

        //get resources which match the given pattern
        List<String> resources = new ArrayList<String>();
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String name = jarEntry.getName();
            if (pattern.matcher(name).matches()) {
                resources.add(name);
            }
        }

        //copy resources into the JOnAS instance deploy directory
        for (String resource: resources) {
            String name = resource.substring(resource.lastIndexOf("/") + 1, resource.length());

            //get the resource
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resource);
            if (inputStream == null) {
                throw new BuildException("Resource " + resource + " cannot be found.");
            }

            File deployDir = new File(new File(getJOnASBase(), "deploy"), name);
            OutputStream outputStream;
            try {
                outputStream = new FileOutputStream(deployDir);
            } catch (FileNotFoundException e) {
                throw new BuildException("File " + deployDir.getAbsolutePath() + " cannot be found", e);
            }

            try {
                outputStream.write(inputStream2Byte(inputStream));
            } catch (IOException e) {
                throw new BuildException("Cannot copy resource " + name + " to " + deployDir.getAbsolutePath(), e);
            } finally {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new BuildException("Cannot close outpustream of the resource " + deployDir.getAbsolutePath(), e);
                }
            }
        }
    }

    /**
     * Convert an inpustream to an array of byte
     * @param inputStream The inpustream
     * @return the array of associated byte
     */
    private byte[] inputStream2Byte(final InputStream inputStream) {
        int length;
        int size = 1024;
        byte [] buffer = new byte[size];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            while ((length = inputStream.read(buffer, 0, size)) != -1) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            throw new BuildException("Cannot convert inpustream to byte[]", e);
        }
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * @param skipOptionalDeployablesCopy Set the skipOptionalDeployablesCopy flag
     */
    public void setSkipOptionalDeployablesCopy(boolean skipOptionalDeployablesCopy) {
        this.skipOptionalDeployablesCopy = skipOptionalDeployablesCopy;
    }
}
