/**
 * 
 */
package gov.va.med.cds.testharness.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author vhaislegberb
 *
 */
public class TemplateJarHelper {

	/**
     * Unjars schema definitions jar file to xsd files and saves them at a pre determined location.
     * 
     * @param filePath path to the jar file which contains schema files
     */
    public static void unjar( String pathToXsdTemplateCache, String templateId ) throws IOException
    {
        InputStream ios = null;
        FileOutputStream fos = null;

        String pathToJar = String.format( "%s/%s.jar", pathToXsdTemplateCache, templateId );
        String unjarDirectoryPath = String.format( "%s/%s/", pathToXsdTemplateCache, templateId );
        
        // delete the previously unjar'd XSDs
        deleteDirectory(unjarDirectoryPath);

        try
        {
            JarFile jarFile = new JarFile( pathToJar );

            Enumeration<JarEntry> enumeration = jarFile.entries();

            while ( enumeration.hasMoreElements() )
            {
                JarEntry jarEntry = ( JarEntry )enumeration.nextElement();
                File file = new File( unjarDirectoryPath, jarEntry.getName() );
                
                if ( jarEntry.isDirectory() )
                {
                    file.mkdirs();
                    continue;
                }

                ios = jarFile.getInputStream( jarEntry );
                fos = new FileOutputStream( file );

                while ( ios.available() > 0 )
                {
                    fos.write( ios.read() );
                }
            }
        }
        finally 
        {
            if(ios != null)
            {
                try{
                    ios.close();
                } 
                catch (Exception e)
                {
                    // eat it.
                }
            }
            
            if(fos != null)
            {
                try{
                    ios.close();
                } 
                catch (Exception e)
                {
                    // eat it.
                }
            }
        }
    }
    
    
    private static void deleteDirectory( String directoryPath ) throws IOException
    {
        File folder = new File(directoryPath);
        String[] files = null;
        if(folder.isDirectory() && (files = folder.list()).length > 0)
        {
            for(String filename : files)
            {
                File f = new File(folder, filename);
                if(f.isDirectory())
                {
                    deleteDirectory( f.getCanonicalPath() );
                }
                else
                {
                    f.delete();
                }
            }
        }
        
        folder.delete();
    }
}
