/* Generated by Together */

package cobalt.deployment.descriptor.dist;

import java.util.Vector;
import java.util.HashMap;
import java.util.Iterator;
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.jar.*;

import cobalt.deployment.descriptor.EjbBundleDescriptor;
import cobalt.deployment.descriptor.ArchiveEntry;
import cobalt.deployment.descriptor.EjbDescriptor;
import cobalt.deployment.descriptor.SessionEjbDescriptor;
import cobalt.deployment.descriptor.EntityEjbDescriptor;
import cobalt.deployment.descriptor.EjbReferenceDescriptor;
import cobalt.deployment.descriptor.ResourceReferenceDescriptor;
import cobalt.deployment.descriptor.xml.ElementNode;
import cobalt.deployment.descriptor.xml.Jeus30EjbBundleNode;
import cobalt.deployment.descriptor.xml.Jeus30EjbNode;
import cobalt.deployment.util.CommonUtil;
import cobalt.deployment.util.EnvironmentManager;
import cobalt.deployment.util.Jeus30XmlUtil;

public class Jeus30EjbBundleDescriptor {
boolean DEBUG = true;
void info(String msg) {
    if ( DEBUG )
        System.out.println(getClass().getName() + '>' + msg);
}
    public Jeus30EjbBundleDescriptor(EjbBundleDescriptor bundles) {
        this.descriptor = bundles;
        ejbs = new Vector();
        securityRoles = new HashMap();
        //cmp = new Jeus30ContainerManaged();
        /*
        try {
            File xmlfile = File.createTempFile("websphere3x", xmlFile, new File(CommonUtil.getTempDir()));
            xmlFile = xmlfile.getAbsolutePath();
            xmlfile.deleteOnExit();
            File tempfile = File.createTempFile("websphere3x", tempDeployableFile, new File(CommonUtil.getTempDir()));
            tempDeployableFile = tempfile.getAbsolutePath();
            tempfile.deleteOnExit();
        } catch ( IOException e) {
            //xmlFile = CommonUtil.getTempDir() + "DD.xml";
        }
        */
        organize();
    }
    public EjbBundleDescriptor getDescriptor(){ return descriptor; }

    public void setDescriptor(EjbBundleDescriptor descriptor){
        this.descriptor = descriptor;
        organize();
    }

    public Vector getEjbs(){ return ejbs; }

    public void setEjbs(Vector ejbs){ this.ejbs = ejbs; }

    void organize() {
	    ejbs.clear();
        Vector ejbvalues = descriptor.getEjbDescriptorValues();
        for ( int i=0 ; i<ejbvalues.size()  ; i++) {
            EjbDescriptor ejb = (EjbDescriptor)ejbvalues.elementAt(i);
            if ( ejb.getEjbType().equals("Session") ) {
                if ( ((SessionEjbDescriptor)ejb).getSessionType().equals("Stateless") )
                	ejbs.addElement(new Jeus30StatelessEjbDescriptor(ejb));
                else
                    ejbs.addElement(new Jeus30StatefulEjbDescriptor(ejb));
            }
            else {
                if ( ejb.getTransactionType().equals("Container") ) {
                	ejbs.addElement(new Jeus30CMPEjbDescriptor(ejb));
                }
                else {
                    ejbs.addElement(new Jeus30BMPEjbDescriptor(ejb));
                }
                /*
                if (((EntityEjbDescriptor)entityEjb.getDescriptor()).isCmp()) {
                    if (cmp == null)
                    	cmp = new Jeus30ContainerManaged();
                    cmp.addEjb(entityEjb.getDbms());
                }
                */
            }
            Iterator iterator = descriptor.getRoleNameIterator();
            while ( iterator.hasNext() ) {
                securityRoles.put(new Jeus30SecurityRole((String)iterator.next()), "");
            }
        }
    }

    public String getDescription(){
            return description;
        }

    public void setDescription(String description){
            this.description = description;
        }

    public String getName() {
        return descriptor.getName();
    }

    public Jeus30ApplicationDescriptor getAppDescriptor(){
            return appDescriptor;
        }

    public void setAppDescriptor(Jeus30ApplicationDescriptor appDescriptor){
            this.appDescriptor = appDescriptor;
        }

    public String getDeployableFileName() {
        //return appDescriptor.getDeployableDirectory() + (appDescriptor.getDeployableDirectory().endsWith(CommonUtil.getDirSep())? "" : CommonUtil.getDirSep())
        //     + appDescriptor.getDeployablePrefix() + CommonUtil.getFileName(descriptor.getFileName());
        return CommonUtil.concatDirectoryFileName(appDescriptor.getDeployableDirectory(),
                                            appDescriptor.getDeployablePrefix() + CommonUtil.getFileName(descriptor.getFileName()) );
    }
    /*public String getXmlFile() {
        return xmlFile;
    }
    public void setXmlFile(String filename) {
        this.xmlFile = filename;
    }*/

    /*
    public String getTempDeployableFile() {
        return tempDeployableFile;
    }
    public void setTempDeployableFile(String filename) {
        this.tempDeployableFile = filename;
    }
    */

    public ElementNode getDocument()
    {
        return Jeus30XmlUtil.getNewJeusEjbBundleNode(this);
    }

    public void archive(/*ElementNode doc*/) {
		CommonUtil.copyFile(descriptor.getFileName(), getDeployableFileName());
		archiveToJar((Jeus30EjbBundleNode)getDocument()/*, getDeployableFileName()*/);
    }

	public void archiveToJar(Jeus30EjbBundleNode doc) {
        File jarFile = null, tempJarFile = null;
        JarOutputStream jos = null;
        FileInputStream jfis = null;
		JarInputStream jis = null;
		JarEntry e = null;
        try {
            jarFile = new File(getDescriptor().getFileName() /*fileName*/);
            jfis = new FileInputStream(jarFile);
            jis = new JarInputStream(jfis);
            jos = ArchiveEntry.getJarOutput(new File(getDeployableFileName()));
			while ((e=jis.getNextJarEntry()) != null) {
				/*if ( e.getName().endsWith("/ejb-jar.xml") )
                    jos.putNextEntry(new JarEntry("META-INF/ejb-jar_" + CommonUtil.getFileNameWithoutExtension(getDeployableFileName()) + ".xml"));
                else */jos.putNextEntry(e);
				byte[] data = new byte[1024];
				int len = 0;
				while ((len=jis.read(data)) >= 0)
					jos.write(data, 0, len);
			}
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
	        try { jis.close(); } catch (Exception e2) { }
	        try { jfis.close(); } catch (Exception e2) { }
	        try { jos.flush(); jos.close(); } catch (Exception e2) { }
        }
		writeDD(doc, getFileName());
	}
	public boolean writeDD(String filename)
	{
		return writeDD(getDocument(), filename);
	}
	public boolean writeDD(ElementNode doc, String filename)
    {
System.out.println("JEUS DD : " + filename);
		try {
            BufferedWriter xmlFos = new BufferedWriter(new java.io.FileWriter(filename));
			xmlFos.write(doc.getXmlString());
            xmlFos.flush();
            xmlFos.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public String getModuleName(){
		if ( moduleName == null || moduleName.equals("") )
            setModuleName(CommonUtil.getFileNameWithoutExtension(getDeployableFileName()));
        return moduleName;
    }

    public void setModuleName(String moduleName){ this.moduleName = moduleName; }

    public HashMap getSecurityRoles(){ return securityRoles; }

    public void setSecurityRoles(HashMap securityRoles){ this.securityRoles = securityRoles; }

    public Jeus30SecurityRole getSecurityRole(String name)
    {
        return (Jeus30SecurityRole)securityRoles.get(name);
    }

    public void putSecurityRole(String roleName, String roleUser)
    {
        //securityRoles.put(roleName, roleUser);
        Jeus30SecurityRole role = (Jeus30SecurityRole)securityRoles.get(roleName);
        role.putUser(roleUser);
    }

    public void removeSecurityRole(String roleName)
    {
        securityRoles.remove(roleName);
    }

    public void removeSecurityRoleUser(String roleName, String roleUser)
    {
        Jeus30SecurityRole role = (Jeus30SecurityRole)securityRoles.get(roleName);
        role.removeUser(roleUser);
    }

    public Iterator getSecurityRoleIterator()
    {
        return securityRoles.keySet().iterator();
	}

	public String getFileName()
	{
		return CommonUtil.concatDirectoryFileName(EnvironmentManager.getServerPropertyValue("jeus_3_0", "Working Temp Dir"),
							"jeus-ejb-dd_" + CommonUtil.getFileNameWithoutExtension(getDeployableFileName()) + ".xml");
	}

/*
    public Jeus30ContainerManaged getCmp(){
            return cmp;
        }

    public void setCmp(Jeus30ContainerManaged cmp){
            this.cmp = cmp;
        }
*/
/*--
    Jeus30EntityEjbDescriptor getFirstEntityEjbDescriptor(){
        for ( int i=0 ; i < ejbs.size() ; i++ )
            if ( ejbs.elementAt(i) instanceof Jeus30EntityEjbDescriptor )
            	return (Jeus30EntityEjbDescriptor)ejbs.elementAt(i);
        return null;
    }
*/
    private EjbBundleDescriptor descriptor;
    private Vector ejbs;
    private String description;
    private Jeus30ApplicationDescriptor appDescriptor;
    private String moduleName;
    private HashMap securityRoles;
    //private String xmlFile = "DD.xml";
    //private String tempDeployableFile = "deployable.jar";
    //private Jeus30ContainerManaged cmp;
}
