package com.siwei.common.core.utils.file;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import com.siwei.common.core.utils.StringUtils;
import net.lingala.zip4j.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UnPackageUtils {
    private static final Logger log = LoggerFactory.getLogger(UnPackageUtils.class);

    public static boolean unPackZip(File zipFile, String destPath, String password) {
        return unPackZip(zipFile, destPath, password, null);
    }

    /**
     * zip文件解压
     *
     * @param destPath 解压文件路径
     * @param zipFile  压缩文件
     * @param password 解压密码(如果有)
     */
    public static boolean unPackZip(File zipFile, String destPath, String password, String encoding) {
        try (ZipFile zip = new ZipFile(zipFile)) {
            /*zip4j默认用GBK编码去解压,这里设置编码为GBK的*/
            if (StringUtils.isEmpty(encoding)) {
                encoding = "GBK";
            }
            zip.setCharset(Charset.forName(encoding));
            // 对 zipFile 进行操作
            // 如果解压需要密码
            if (zip.isEncrypted()) {
                zip.setPassword(password.toCharArray());
            }
            zip.extractAll(destPath);
            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static boolean unPackZip(String zipFile, String destPath, String password) {
        return unPackZip(new File(zipFile), destPath, password, null);
    }

    public static boolean unPackZip(String zipFile, String destPath, String password, String encoding) {
        return unPackZip(new File(zipFile), destPath, password, encoding);
    }

}
