package com.zxhl.cms.utils

import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import java.io.*
import java.text.DecimalFormat


/**
 * Created by gaoleichao on 2018/8/31.
 */
object FileUtils {

    fun getDownLoadDiectory(): String {
        var photoDir = AppContext.get().getExternalFilesDir("download")
        var path = if (photoDir != null) photoDir!!.absolutePath
        else
            Environment.getExternalStorageDirectory().absolutePath + File.separator + Constant.Param.mPacketName + File.separator + "download"

        return path
    }

    fun getWebViewCacheDiectory(): String {
        return AppContext.get().filesDir.absolutePath + "/webcache"
    }

    fun getPhotoDirectory(): String {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath + File.separator + "photos"
        }
        var photoDir = AppContext.get().getExternalCacheDir()
        var path = if (photoDir != null) photoDir?.absolutePath
        else
            Environment.getExternalStorageDirectory().absolutePath + File.separator + Constant.Param.mPacketName + File.separator + "photos"
        return path + File.separator + "photos"
    }

    fun getUpdateApkDirectory(): String {
        var photoDir = AppContext.get().getExternalFilesDir("updateApk")
        var path = if (photoDir != null) photoDir?.absolutePath
        else
            Environment.getExternalStorageDirectory().absolutePath + File.separator + Constant.Param.mPacketName + File.separator + "updateApk"
        return path
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    fun delAllFile(path: String): Boolean {
        var flag = false
        val file = File(path)
        if (!file.exists()) {
            return flag
        }
        if (!file.isDirectory) {
            return flag
        }
        val tempList = file.list()
        var temp: File? = null
        for (i in tempList!!.indices) {
            if (path.endsWith(File.separator)) {
                temp = File(path + tempList[i])
            } else {
                temp = File(path + File.separator + tempList[i])
            }
            if (temp.isFile) {
                temp.delete()
            }
            if (temp.isDirectory) {
                delAllFile(path + "/" + tempList[i])//先删除文件夹里面的文件
//                delFolder(path + "/" + tempList[i])//再删除空文件夹
                flag = true
            }
        }
        return flag
    }

    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    fun getAutoFileOrFilesSize(filePath: String): String {
        val file = File(filePath)
        var blockSize: Long = 0
        try {
            if (file.isDirectory) {
                blockSize = getFileSizes(file)
            } else {
                blockSize = getFileSize(file)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return FormetFileSize(blockSize)
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private fun getFileSizes(f: File): Long {
        var size: Long = 0
        val flist = f.listFiles()
        try {
            for (i in flist!!.indices) {
                if (flist[i].isDirectory) {
                    size = size + getFileSizes(flist[i])
                } else {
                    size = size + getFileSize(flist[i])
                }
            }
        } catch (e: Exception) {

        }
        return size
    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private fun getFileSize(file: File): Long {
        var size: Long = 0
        try {
            if (file.exists()) {
                var fis: FileInputStream? = null
                fis = FileInputStream(file)
                size = fis?.available().toLong()
            } else {
                file.createNewFile()
            }
        } catch (e: Exception) {

        }
        return size
    }

    fun getCacheFileSize(): String {
        val file1 = AppContext.get().cacheDir
        val file2 = AppContext.get().externalCacheDir
        val fileSizes = getFileSizes(file1)
        val fileSizes2 = getFileSizes(file2!!)
        return FormetFileSize(fileSizes + fileSizes2)
    }

    fun clearAllCache(): Boolean {
        val externalCacheDir = AppContext.get().externalCacheDir
        val cacheDir = AppContext.get().cacheDir
        var result = false
        if (cacheDir != null) {
            result = delAllFile(cacheDir?.absolutePath)
        }
        if (externalCacheDir != null) {

            result = delAllFile(externalCacheDir?.absolutePath) || result//原生是真 或者现在是true就是true
        }
        return result
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    private fun FormetFileSize(fileS: Long): String {
        val df = DecimalFormat("#.00")
        var fileSizeString = ""
        val wrongSize = "0B"
        if (fileS == 0L) {
            return wrongSize
        }
        if (fileS < 1024) {
            fileSizeString = df.format(fileS.toDouble()) + "B"
        } else if (fileS < 1048576) {
            fileSizeString = df.format(fileS.toDouble() / 1024) + "KB"
        } else if (fileS < 1073741824) {
            fileSizeString = df.format(fileS.toDouble() / 1048576) + "MB"
        } else {
            fileSizeString = df.format(fileS.toDouble() / 1073741824) + "GB"
        }
        return fileSizeString
    }

    /**
     * 保存视频
     * @param context
     * @param file
     */
     fun saveVideo(context: Context, file: File) {
        //是否添加到相册
        val localContentResolver: ContentResolver = context.getContentResolver()
        val localContentValues = getVideoContentValues(context, file, System.currentTimeMillis())
        val localUri: Uri? = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues)
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri))
    }

    fun getVideoContentValues(paramContext: Context?, paramFile: File, paramLong: Long): ContentValues {
        val localContentValues = ContentValues()
        localContentValues.put("title", paramFile.name)
        localContentValues.put("_display_name", paramFile.name)
        localContentValues.put("mime_type", "video/mp4")
        localContentValues.put("datetaken", java.lang.Long.valueOf(paramLong))
        localContentValues.put("date_modified", java.lang.Long.valueOf(paramLong))
        localContentValues.put("date_added", java.lang.Long.valueOf(paramLong))
        localContentValues.put("_data", paramFile.absolutePath)
        localContentValues.put("_size", java.lang.Long.valueOf(paramFile.length()))
        return localContentValues
    }


}