package com.jianrmod.plugins.harmony.Tools;

import com.kaopiz.kprogresshud.KProgressHUD;

import com.zip4j.core.ZipFile;
import com.zip4j.exception.ZipException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ZipUtils {
    public static List<File> unzip(File zipFile, String descDir, final KProgressHUD hud) {

        List<File> _list = new ArrayList<>();
        byte[] _byte = new byte[1024 * 1024];
        try {
            File descDirPath = new File(descDir);
            if (!descDirPath.exists()) {
                descDirPath.mkdirs();
            }

            System.out.println("文件：" + zipFile.exists());
            try {
                final ZipFile _zipFile = new ZipFile(zipFile);
                _zipFile.setFileNameCharset("GBK");  //设置编码格式（支持中文）
                if (!_zipFile.isValidZipFile()) {     //检查输入的zip文件是否是有效的zip文件
                    throw new ZipException("压缩文件不合法,可能被损坏.");
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            final int done = _zipFile.getProgressMonitor().getPercentDone();
                            Utils.handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    hud.setLabel(done + "%");
                                }
                            });
                            if(done>=100){
                                break;
                            }
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
                _zipFile.extractAll(descDir); //解压
            } catch (ZipException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        zipFile.renameTo(new File(zipFile.getAbsolutePath().replace(zipFile.getName(),"")+"/"+zipFile.getName()+".unzip"));
        Utils.handler.post(new Runnable() {
            @Override
            public void run() {
                hud.dismiss();
            }
        });
        return _list;
    }
}
