package com.swago.baseswago.util

import java.io.*
import java.lang.Exception
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipFile

/**
 *@date 2022/2/12 11:44
 *description:
 */
object FileUtil {

    fun deleteFile(file: File) {
        if (file.isDirectory) {
            file.list()?.forEach {
                deleteFile(File(file, it))
            }
        }
        file.delete()
    }

    fun upZipFile(zipFile: String, zipUpPath: String) {
        if (zipFile.isEmpty()) return
        if (!zipFile.endsWith(".zip")) {
            deleteFile(File(zipFile))
        }
        val file = File(zipFile)
        try {
            val zipFile = ZipFile(file)
            val zipUpFile = File(zipUpPath)
            if (!zipUpFile.exists()) {
                zipUpFile.mkdirs()
            }
            val zList: Enumeration<*> = zipFile.entries()
            var ze: ZipEntry? = null
            val buf = ByteArray(1024)

            while (zList.hasMoreElements()) {
                ze = zList.nextElement() as ZipEntry
                if (ze.isDirectory) {
                    val tempPath = ze.name
                    var dirstr = zipUpPath + tempPath
                    dirstr = String(dirstr.toByteArray(charset("8859_1")))
                    val f = File(dirstr)
                    f.mkdir()
                    continue
                }

                val tempPath = ze.getName()
                var readLen = 0
                val os: OutputStream =
                    BufferedOutputStream(FileOutputStream(getRealFileName(zipUpPath, tempPath)))
                val inputStream: InputStream = BufferedInputStream(zipFile.getInputStream(ze))
                try {
                    while (inputStream.read(buf, 0, 1024).also { readLen = it } != -1) {
                        os.write(buf, 0, readLen)
                    }
                } catch (e: Exception) {
                    file.delete()
                    e.printStackTrace()
                } finally {
                    try {
                        inputStream.close()
                        os.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }

            }
            zipFile.close()
        }catch (e:Exception){
            e.printStackTrace()
        }finally {

        }


    }


    private fun getRealFileName(baseDir: String, absFileName: String): File {
        val dirs = absFileName.split("/").toTypedArray()
        var lastDir = baseDir
        return if (dirs.size > 1) {
            for (i in 0 until dirs.size - 1) {
                lastDir += dirs[i] + "/"
                val dir = File(lastDir)
                if (!dir.exists()) {
                    dir.mkdirs()
                }
            }
            val ret = File(lastDir, dirs[dirs.size - 1])
            ret
        } else {
            File(baseDir, absFileName)
        }
    }

}