/**
 * JaDOrT: JASMINe Deployment Orchestration Tool
 * Copyright (C) 2008-2009 Bull S.A.S.
 * Copyright (C) 2008-2009 France Telecom R&D
 * Contact: jasmine@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: ApplicationBean.java 5660 2009-11-30 18:15:44Z alitokmen $
 * --------------------------------------------------------------------------
 */
package org.ow2.jasmine.jadort.api.entities.deployment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.ow2.util.archive.api.ArchiveException;
import org.ow2.util.archive.api.IArchive;
import org.ow2.util.archive.impl.ArchiveManager;
import org.ow2.util.ee.deploy.api.deployable.IDeployable;
import org.ow2.util.ee.deploy.api.deployable.OSGiDeployable;
import org.ow2.util.ee.deploy.impl.helper.DeployableHelper;
import org.ow2.util.ee.deploy.impl.helper.DeployableHelperException;

/**
 * Bean that represents a Java EE application.
 * 
 * @author Malek Chahine
 * @author Remy Bresson
 * @author S. Ali Tokmen
 */
@Entity(name = "JaDOrT_ApplicationBean")
public class ApplicationBean implements Serializable {

    /**
     * Different application types.<br>
     * <br>
     * We don't use an enum here to preserve compatibility with IIOP runtimes on
     * Java EE 5. You can check out the bug report and comments on
     * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6277781 for details.
     */
    public static final class ApplicationType implements Serializable {

        private static final long serialVersionUID = 9017413540288729033L;

        public static final ApplicationType JAVA_EE = new ApplicationType("JAVA_EE");

        public static final ApplicationType OSGI = new ApplicationType("OSGI");

        private static final ApplicationType[] values = new ApplicationType[] {ApplicationType.JAVA_EE, ApplicationType.OSGI};

        private String applicationType;

        /**
         * @param applicationType ApplicationType.
         */
        private ApplicationType(final String applicationType) {
            this.applicationType = applicationType;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean equals(final Object object) {
            if ((object != null) && (object instanceof ApplicationType)) {
                ApplicationType applicationType = (ApplicationType) object;
                if (applicationType.applicationType.equals(this.applicationType)) {
                    return true;
                }
            }

            return false;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public int hashCode() {
            return this.applicationType.hashCode();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public String toString() {
            return this.applicationType;
        }

        /**
         * @return All ActionState values.
         */
        public static ApplicationType[] values() {
            return ApplicationType.values;
        }

        /**
         * Get the ActionState for a string.
         * 
         * @param string ActionState string.
         * @return ActionState for that string.
         */
        public static ApplicationType valueOf(final String string) {
            for (ApplicationType applicationType : ApplicationType.values) {
                if (applicationType.applicationType.equals(string)) {
                    return applicationType;
                }
            }

            throw new IllegalArgumentException("Unknown value: " + string);
        }
    }

    /**
     * Auto-generated serial version ID.
     */
    private static final long serialVersionUID = -8995544046252693883L;

    /**
     * Auto-generated identifier of the ApplicationBean in the database.
     */
    @Id
    @GeneratedValue
    private Integer id;

    /**
     * Application name
     */
    private String name;

    /**
     * Application version
     */
    private String version;

    /**
     * Application type
     */
    private ApplicationType applicationType;

    /**
     * Application archive file
     */
    private File file;

    /**
     * Application policy
     */
    private String policy;

    /**
     * Application state
     */
    private String state;

    /**
     * Application bean constructor, sets the type as
     * {@link ApplicationType#JAVA_EE}.
     */
    public ApplicationBean() {
        this.applicationType = ApplicationType.JAVA_EE;
    }

    /**
     * Application bean constructor. Build a application bean from his archive
     * file.
     * 
     * @param file The archive file.
     * @throws FileNotFoundException Throw if the archive file is not found.
     * @throws DeployableHelperException Throw if the archive hasn't any
     *         deployable.
     * @throws ArchiveException Throw if the file given isn't a archive.
     */
    public ApplicationBean(final File file) throws FileNotFoundException, DeployableHelperException, ArchiveException {
        this();

        if (!file.exists()) {
            throw new FileNotFoundException("File '" + file + "' not found");
        }
        this.file = file;

        IArchive archive;
        IDeployable<?> deployable;

        try {
            archive = ArchiveManager.getInstance().getArchive(file);
            deployable = DeployableHelper.getDeployable(archive);
            if (deployable == null) {
                throw new NullPointerException();
            }
        } catch (NullPointerException e) {
            throw new ArchiveException("File '" + file + "' not valid");
        }

        this.name = deployable.getModuleName();
        this.version = archive.getMetadata().get("Implementation-Version");

        if (OSGiDeployable.class.isInstance(deployable)) {
            this.applicationType = ApplicationType.OSGI;
        }

        if (this.version != null) {
            final String versioningStyleVersion = "-version" + this.version;
            if (this.name.endsWith(versioningStyleVersion)) {
                this.name = this.name.substring(0, this.name.length() - versioningStyleVersion.length());
            }

            final String mavenStyleVersion = "-" + this.version;
            if (this.name.endsWith(mavenStyleVersion)) {
                this.name = this.name.substring(0, this.name.length() - mavenStyleVersion.length());
            }
        }
    }

    /**
     * Application bean constructor with only the application name
     * 
     * @param name Application name
     */
    public ApplicationBean(final String name) {
        this();

        this.name = name;
    }

    /**
     * Application bean constructor from application name and application
     * versions.
     * 
     * @param name Application name
     * @param version Application version
     */
    public ApplicationBean(final String name, final String version) {
        this();

        this.name = name;
        this.version = version;
    }

    /**
     * Get the application id
     * 
     * @return the application id
     */
    public Integer getId() {
        return this.id;
    }

    /**
     * Set the application id
     * 
     * @param id the application id
     */
    public void setId(final Integer id) {
        this.id = id;
    }

    /**
     * Name getter
     * 
     * @return Application name
     */
    public String getName() {
        return this.name;
    }

    /**
     * Name setter
     * 
     * @param name Application name
     */
    public void setName(final String name) {
        this.name = name;
    }

    /**
     * Application type getter
     * 
     * @return Application type
     */
    public ApplicationType getApplicationType() {
        return this.applicationType;
    }

    /**
     * Application type setter
     * 
     * @param applicationType Application type
     */
    public void setApplicationType(final ApplicationType applicationType) {
        this.applicationType = applicationType;
    }

    /**
     * Version getter
     * 
     * @return Application version
     */
    public String getVersion() {
        return this.version;
    }

    /**
     * Version setter
     * 
     * @param version Application version
     */
    public void setVersion(final String version) {
        this.version = version;
    }

    /**
     * File getter
     * 
     * @return The application file.
     */
    public File getFile() {
        return this.file;
    }

    /**
     * File(archive) setter. Don't reload application. Don't open the archive to
     * find deployable.
     * 
     * @param file Application file
     */
    public void setFile(final File file) {
        this.file = file;
    }

    /**
     * Policy getter
     * 
     * @return Application policy
     */
    public String getPolicy() {
        return this.policy;
    }

    /**
     * Application policy setter
     * 
     * @param policy Application policy
     */
    public void setPolicy(final String policy) {
        this.policy = policy;
    }

    /**
     * State getter
     * 
     * @return Application state
     */
    public String getState() {
        return this.state;
    }

    /**
     * State setter
     * 
     * @param state Application state
     */
    public void setState(final String state) {
        this.state = state;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(this.getClass().getSimpleName());
        sb.append("[name='");
        sb.append(this.name);
        if (this.version != null) {
            sb.append("', version='");
            sb.append(this.version);
        }
        sb.append("']");
        return sb.toString();
    }

    /**
     * {@inheritDoc}
     * 
     * @return true if <code>obj</code> is an {@link ApplicationBean} and the
     *         {@link ApplicationBean#getId()} is the same for both objects,
     *         false otherwise.
     */
    @Override
    public boolean equals(final Object obj) {
        if (obj != null && obj instanceof ApplicationBean) {
            ApplicationBean other = (ApplicationBean) obj;
            if (this.id != null && other.id != null) {
                return this.id.equals(other.id);
            }
        }

        // Else not same type or some parts are null
        return false;
    }

}
