package com.sunny.app.soft.timberkeyboardnew.tools

import android.graphics.drawable.Drawable
import android.util.Log
import android.view.inputmethod.EditorInfo
import com.sunny.app.soft.timberkeyboardnew.App
import com.sunny.app.soft.timberkeyboardnew.ui.listener.ApplyListener
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.util.zip.ZipInputStream


object ZipTools {
    fun unzip(zipFilePath: String?, destDirectory: String, listener: ApplyListener) {
        var destDir = File(destDirectory)
        if (!destDir.exists()) {
            destDir.mkdirs()
        }
        var test = "${App.appContext.cacheDir}"
        val zipIn = ZipInputStream(FileInputStream(zipFilePath))
        var entry = zipIn.nextEntry

        var unzipDir = ""
        while (entry != null) {
            val filePath = test + File.separator + entry.name
            if (!entry.isDirectory) {
                extractFile(zipIn, filePath)
            } else {
                val dir = File(filePath)
                dir.mkdir()
                // /data/user/0/com.sunny.tools.app.soft.test/cache/9/skin_9/
                unzipDir = filePath
            }
            zipIn.closeEntry()
            entry = zipIn.nextEntry
        }
        val replaceAfterLast = unzipDir.substring(0, unzipDir.length-1)
        Log.d(App.TAG, "--new unzip=$replaceAfterLast")
        listener.applyListener(true,replaceAfterLast)
        zipIn.close()
    }

    private fun extractFile(zipIn: ZipInputStream, filePath: String) {
        val bos = BufferedOutputStream(FileOutputStream(filePath))
        val bytesIn = ByteArray(4096)
        var read: Int
        while ((zipIn.read(bytesIn).also { read = it }) != -1) {
            bos.write(bytesIn, 0, read)
        }
        bos.close()
    }

    fun getUnzipPath(skinNumber: String): String {
        val s = "${App.appContext.cacheDir}/skin_${skinNumber}"
        return s
    }


    fun loadDrawableFromAsset(fileName: String): Drawable? {
        val assetManager = App.appContext.assets
        var input: InputStream? = null
        return try {
            input = assetManager.open(fileName)
            Drawable.createFromStream(input, null)
        } catch (e: IOException) {
            Log.e("AssetHelper", "Could not load drawable from asset: $fileName")
            null
        } finally {
            if (input!= null) {
                try {
                    input.close()
                } catch (e: IOException) {
                    Log.e(
                        "AssetHelper",
                        "Could not close input stream for asset: $fileName"
                    )
                }
            }
        }
    }
    fun getTextForImeAction(imeOptions: Int): Int {
        return imeOptions and EditorInfo.IME_MASK_ACTION
    }

}
