package com.grkj.iscs.util

import android.content.Context
import android.os.Environment
import com.grkj.iscs.util.log.LogUtil
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.BufferedReader
import java.io.File
import java.io.File.separator
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStreamReader

object FileUtil {

    private const val ROOT_APP = "iscs"
    val DOWNLOAD_DIR = "${separator}download"
    val LOG_DIR = "${separator}log"
    val CRASH_DIR = "${separator}crash"

    /**
     * @param permissionType：0：默认（根目录>私有可见文件缓存）；1：私有可见缓存；2：私有可见文件；3：私有缓存；4：私有文件
     */
    fun getRootFolder(mContext: Context, permissionType: Int = 0): File? {
        var rootFile: File? = null
        when (permissionType) {
            1 -> {
                rootFile = File(mContext.externalCacheDir, "$separator$ROOT_APP")
            }

            2 -> {
                rootFile = File(mContext.getExternalFilesDir(null), "$separator$ROOT_APP")
            }

            3 -> {
                rootFile = File(mContext.cacheDir, "$separator$ROOT_APP")
            }

            4 -> {
                rootFile = File(mContext.filesDir, "$separator$ROOT_APP")
            }

            else -> {
                try {
                    rootFile =
                        File(Environment.getExternalStorageDirectory(), "$separator$ROOT_APP")
                    if (rootFile.exists()) {
                        return rootFile
                    } else {
                        val isSucc = rootFile.mkdirs()
                        if (isSucc) return rootFile
                    }
                } catch (e: Exception) {
//                        d("创建文件夹异常",e)
                }
                rootFile = File(mContext.getExternalFilesDir(null), "$separator$ROOT_APP")
                if (rootFile.exists()) {
                    return rootFile
                } else {
                    val isSucc = rootFile.mkdirs()
                    if (isSucc) return rootFile
                }
//                    d("创建文件夹失败2：${rootFile?.absolutePath}")
                return null
            }
        }
        rootFile?.let {
            if (it.exists()) {
                return it
            } else {
                val isSucc = it.mkdirs()
                if (isSucc) return it
            }
        }
//            d("创建文件夹失败：${rootFile?.absolutePath}")
        return null
    }


    /**
     * 单个文件复制
     */
    fun copyfile(srcFile: File, destFile: File) {

        var fis = FileInputStream(srcFile);
        var fos = FileOutputStream(destFile)

        var bis = BufferedInputStream(fis)
        var bos = BufferedOutputStream(fos)


        var buf = ByteArray(1024)

        var len = 0;
        while (true) {
            len = bis.read(buf)
            if (len == -1) break;
            bos.write(buf, 0, len)
        }
        fis.close()
        fos.close()

    }

    /**
     * 带文件夹复制
     */
    fun copyDirToDir(srcFile: File, destFile: File) {
        for (f in srcFile.listFiles()) {
            //是文件就拷贝
            var newfile = File(destFile.absolutePath, f.name)
            if (f.isFile) {
                LogUtil.i("${f.absolutePath}-->${newfile.absolutePath}")
                copyfile(f, newfile)
            } else { //如果是目录就递归复制
                //如果目标文件不存在，则创建
                if (!newfile.exists()) {
                    if (!newfile.mkdir()) return
                }
                copyDirToDir(f, newfile)
            }
        }
        return
    }

    fun readTxt(path: String?): String {
        var str = ""
        try {
            val urlFile = File(path)
            val isr = InputStreamReader(FileInputStream(urlFile), "UTF-8")
            val br = BufferedReader(isr)

            var mimeTypeLine: String? = null
            while ((br.readLine().also { mimeTypeLine = it }) != null) {
                str += mimeTypeLine
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return str
    }
}