package sikd.sikd5.sikd5bean.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 *
 * @author soraturaes
 */
public class UnzipFileUtil {
    String OUTPUT_FOLDER = "";

    /**
     * method unZipIt
     * @param zipFile
     * @param outputFolder
     * @param jenisFile
     * @return String
     * @throws Exception
     */
    public String unZipIt(String zipFile, String outputFolder, String jenisFile) throws Exception{
     byte[] buffer = new byte[1024];
//     try{    		
    	//create output directory is not exists
    	File folder = new File(OUTPUT_FOLDER);
    	if(!folder.exists()){
    		folder.mkdir();
    	}
    		
    	//get the zip file content
    	ZipInputStream zis = 
    		new ZipInputStream(new FileInputStream(zipFile));
    	//get the zipped file list entry
    	ZipEntry ze = zis.getNextEntry();
        String fileName="";
    		
    	if(ze!=null){		
    	   fileName = ze.getName();
           if( !fileName.trim().endsWith(jenisFile.trim()) )
               throw new Exception("Jenis Berkas Yang Terdapat Di Dalam Berkas zip Tidak Sesuai Dengan Permintaan ("+jenisFile+")");
           
           File newFile = new File(outputFolder + File.separator + fileName);
                
           System.out.println("file unzip : "+ newFile.getAbsoluteFile());
                
            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
              
            FileOutputStream fos = new FileOutputStream(newFile);             

            int len;
            while ((len = zis.read(buffer)) > 0) {
       		fos.write(buffer, 0, len);
            }
        		
            fos.close();   
//            ze = zis.getNextEntry();
    	}
    	
        zis.closeEntry();
    	zis.close();
    	        
    	System.out.println("Done");
        return fileName;
    		
//    }catch(IOException ex){
//       ex.printStackTrace(); 
//    }
   }    
    
    /**
     * method unZipIt
     * @param zipFile
     * @param outputFolder
     */
    public void unZipIt(String zipFile, String outputFolder){
     byte[] buffer = new byte[1024];
     try{
    		
    	//create output directory is not exists
    	File folder = new File(OUTPUT_FOLDER);
    	if(!folder.exists()){
    		folder.mkdir();
    	}
    		
    	//get the zip file content
    	ZipInputStream zis = 
    		new ZipInputStream(new FileInputStream(zipFile));
    	//get the zipped file list entry
    	ZipEntry ze = zis.getNextEntry();
    		
    	while(ze!=null){
    			
    	   String fileName = ze.getName();
           File newFile = new File(outputFolder + File.separator + fileName);
                
           System.out.println("file unzip : "+ newFile.getAbsoluteFile());
                
            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
              
            FileOutputStream fos = new FileOutputStream(newFile);             

            int len;
            while ((len = zis.read(buffer)) > 0) {
       		fos.write(buffer, 0, len);
            }
        		
            fos.close();   
            ze = zis.getNextEntry();
    	}
    	
        zis.closeEntry();
    	zis.close();
    		
    	System.out.println("Done");
    		
    }catch(IOException ex){
        Logger.getLogger(UnzipFileUtil.class.getName());
        
    }
   }    
    
    public static void cekFolder(String foldernya) {
        File f = new File(foldernya);
        if (!f.isDirectory()) f.mkdirs();
        f = null;
    }
    public static String uploadPathnya(String uploadpath, short tahun) {
        return uploadpath + File.separator + tahun + File.separator + "sofcopy" + File.separator + "zip" + File.separator;
    }
    public static String uploadPathUnzipnya(String uploadpath, short tahun) {
        return uploadpath + File.separator + tahun + File.separator + "sofcopy" + File.separator + "unzip" + File.separator;
    }
    public static String dateToString(Date tgl){
        if (tgl != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                return sdf.format(tgl);
            } catch (Exception ex) {
                return "";
            }
        }
        else return "";
    }
    
//    public static String[] simpanExtract(String uploadPath, String kdikd, String kodeSatker, short tahun, byte[] berkasnya) throws Exception {
    public static String[] simpanExtract(String uploadPath, byte[] berkasnya) throws Exception {
        Date dd = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(dd);
        short tahun = (short)gc.get(Calendar.YEAR);
        cekFolder(uploadPathnya(uploadPath, tahun));
        cekFolder(uploadPathUnzipnya(uploadPath, tahun));
//        String zipFileNameTemp = uploadPathnya(uploadPath, tahun) + tahun + kodeSatker.trim() + kdikd + "_temp.zip";
        String zipFileNameTemp = uploadPathnya(uploadPath, tahun) + dd.getTime() + "_temp.zip";
        File zfileTemp = new File(zipFileNameTemp);
        FileOutputStream fos = new FileOutputStream(zfileTemp);
        fos.write(berkasnya);
        fos.flush();
        fos.close();
        
        String xmlFileName = getXmlFileName(zfileTemp);
        String zipFileName = "";
        
        if( xmlFileName!=null && !xmlFileName.trim().equals("")){
            String ss = xmlFileName.trim().substring(0, xmlFileName.trim().length()-4);
            zipFileName = ss+ "_" + dd.getTime();
            xmlFileName = uploadPathUnzipnya(uploadPath, tahun)+xmlFileName;
        }
        if( zipFileName!=null && !zipFileName.trim().equals("") ){
            zipFileName = uploadPathnya(uploadPath, tahun)+zipFileName+".zip";
        }
        System.out.println("zipFileName " + zipFileName);
        
        File zipFile = new File(zipFileName);
        fos = new FileOutputStream(zipFile);
        fos.write(berkasnya);
        fos.flush();
        fos.close();
        if( zfileTemp.exists() ){
            zfileTemp.deleteOnExit();
        }
        System.out.println("xmlFileName " + xmlFileName);
        File fx = new File(xmlFileName);
        if (fx.exists()) fx.delete();
        UnzipFileUtil ufs = new UnzipFileUtil();
        ufs.unZipIt(zipFileName, uploadPathUnzipnya(uploadPath, tahun), "xml");
        return new String[]{zipFileName, xmlFileName};
    }
    
    private static String getXmlFileName(File zf) throws Exception{
        ZipFile zipf = new ZipFile(zf);
        Enumeration enu = zipf.entries();
        boolean found = false;
        String result = "";
        while (enu.hasMoreElements() && found == false) {
            ZipEntry zz = (ZipEntry) enu.nextElement();
            if (zz.getName().toLowerCase().trim().endsWith(".xml")) {
                found = true;
                result = zz.getName();
            }
        }
        return result;
    }
    
    
}