package _VisualDVM.Passes.All;
import Common.Passes.Pass;
import Common.Utils.Utils_;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UnzipFolderPass<T> extends Pass<T> {
    protected String src;
    protected String dst;
    protected boolean clean_dst = true;
    @Override
    protected boolean needsAnimation() {
        return false;
    }
    @Override
    protected boolean canStart(Object... args) {
        src = (String) args[0];
        dst = (String) args[1];
        clean_dst = args.length > 2 && (boolean) args[2];
        return true;
    }
    @Override
    protected void performPreparation() throws Exception {
        if (clean_dst)
            Utils_.forceDeleteWithCheck(new File(dst));
    }
    @Override
    protected void body() throws Exception {
        // Open the zip file
        ZipFile zipFile = new ZipFile(src);
        Enumeration<?> enu = zipFile.entries();
        int total = zipFile.size();
        int count = 0;
        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();
            String name = zipEntry.getName();
            // long size = zipEntry.getSize();
            // long compressedSize = zipEntry.getCompressedSize();
            //  form.ShowMessage1(name);
            //  form.ShowProgress(total, count, true);
            count++;
                  /*  String.format("name: %-20s | size: %6d | compressed size: %6d\n",
                    name, size, compressedSize));

                   */
            // Do we need to create a directory ?
            File file = Paths.get(dst, name).toFile();
            if (name.endsWith("/")) {
                file.mkdirs();
                continue;
            }
            File parent = file.getParentFile();
            if (parent != null) {
                parent.mkdirs();
            }
            // Extract the file
            InputStream is = zipFile.getInputStream(zipEntry);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = is.read(bytes)) >= 0) {
                fos.write(bytes, 0, length);
            }
            is.close();
            fos.close();
        }
        zipFile.close();
        // unpack();
    }
    @Override
    public String getDescription() {
        return "Распаковка папки";
    }
}
