package com.yutou.jianr_mg.Tools;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.yutou.jianr_mg.Data.AppData;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.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 {
                ZipFile _zipFile = new ZipFile(zipFile);
                _zipFile.setFileNameCharset("GBK");  //设置编码格式（支持中文）
                if (!_zipFile.isValidZipFile()) {     //检查输入的zip文件是否是有效的zip文件
                    throw new ZipException("压缩文件不合法,可能被损坏.");
                }
                new Thread(() -> {
                    while (true) {
                        int done = _zipFile.getProgressMonitor().getPercentDone();
                        AppData.handler.post(() -> 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();
        }
        AppData.handler.post(hud::dismiss);
        return _list;
    }
}
