package cn.yyxx.eyuancomm.base.ext

import java.io.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

/**
 * @author #Suyghur.
 * Created on 2022/01/11
 */

fun File.zipAll(zipFile: String) {
    ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use {
        it.use { zos ->
            zos.zipFiles(this, "")
        }
    }
}

private fun ZipOutputStream.zipFiles(sourceFile: File, parentDirPath: String) {
    val data = ByteArray(2048)
    for (f in sourceFile.listFiles()) {
        if (f.isDirectory) {
            val entry = ZipEntry(f.name + File.separator)
            entry.time = f.lastModified()
            entry.isDirectory
            entry.size = f.length()
            putNextEntry(entry)
            zipFiles(f, f.name)
        } else {
            // 过滤zip和cache
            if (!f.name.contains(".zip")) {
                FileInputStream(f).use { fi ->
                    BufferedInputStream(fi).use { origin ->
                        val path = parentDirPath + File.separator + f.name
                        val entry = ZipEntry(path)
                        entry.time = f.lastModified()
                        entry.isDirectory
                        entry.size = f.length()
                        putNextEntry(entry)
                        while (true) {
                            val readBytes = origin.read(data)
                            if (readBytes == -1) {
                                break
                            }
                            write(data, 0, readBytes)
                        }
                    }
                }
            } else {
                closeEntry()
                close()
            }
        }
    }
}