package tool

import (
    "archive/tar"
    "archive/zip"
    "bytes"
    "compress/gzip"
    "golang.org/x/text/encoding/simplifiedchinese"
    "golang.org/x/text/transform"
    "io"
    "io/ioutil"
    "os"
    "path/filepath"
)

//Unzip 解压 zip 包到指定目录
func Unzip(zipFile string, destDir string) error {
    zipReader, err := zip.OpenReader(zipFile)
    if err != nil {
        return err
    }
    defer zipReader.Close()
    var decodeName string
    for _, f := range zipReader.File {
        if f.Flags == 0 {
            //如果标致位是0  则是默认的本地编码   默认为gbk
            i := bytes.NewReader([]byte(f.Name))
            decoder := transform.NewReader(i, simplifiedchinese.GB18030.NewDecoder())
            content, _ := ioutil.ReadAll(decoder)
            decodeName = string(content)
        } else {
            //如果标志为是 1 << 11也就是 2048  则是utf-8编码
            decodeName = f.Name
        }
        fpath := filepath.Join(destDir, decodeName)
        if f.FileInfo().IsDir() {
            os.MkdirAll(fpath, os.ModePerm)
        } else {
            if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
                return err
            }
            inFile, err := f.Open()
            if err != nil {
                return err
            }
            defer inFile.Close()
            outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
            if err != nil {
                return err
            }
            defer outFile.Close()
            _, err = io.Copy(outFile, inFile)
            if err != nil {
                return err
            }
        }
    }
    return nil
}


// UnTarGz 解压缩 tar.gz 到指定文件夹
func UnTarGz(tarGzFile string, destDir string) error {
    gzipStream, err := os.Open(tarGzFile)
    if err != nil {
        return err
    }
    uncompressedStream, err := gzip.NewReader(gzipStream)
    if err != nil {
        return err
    }
    tarReader := tar.NewReader(uncompressedStream)
    for true {
        header, err := tarReader.Next()
        if err == io.EOF {
            break
        }
        if err != nil {
            return err
        }
        switch header.Typeflag {
        case tar.TypeDir:
            outputPath := filepath.Join(destDir, header.Name)
            if err := os.MkdirAll(outputPath, 0755); err != nil {
                return err
            }
        case tar.TypeReg:
            outputPath := filepath.Join(destDir, header.Name)
            outFile, err := os.Create(outputPath)
            if err != nil {
                return err
            }
            if _, err := io.Copy(outFile, tarReader); err != nil {
                return err
            }
            outFile.Close()
        default:
            return err
        }
    }
    return nil
}