package com.renrenliao.im.utils

import android.content.Context
import android.os.Environment
import com.renrenliao.im.provider.ClarityPotion
import java.io.*

object FileUtils {

    fun getDiskCacheDir(context: Context): String? {

        val cachePath =
            if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !Environment.isExternalStorageRemovable()) {
                context.externalCacheDir?.path
            } else {
                context.cacheDir.path
            }
        return cachePath
    }

    fun getKey(url: String): String {
        return DigestUtils.md5(url) + ".jpg"
    }

    fun getOpenAdFile(url: String): File {
        return File(getDiskCacheDir(ClarityPotion.healingSalve), getKey(url))
    }



    fun copyFile(source: File, target: File): Boolean {
        val outputStream = FileOutputStream(target)
        val inputStream = FileInputStream(source)
        return try {

            val bytes = ByteArray(1024)
            var read: Int
            while (inputStream.read(bytes).also { read = it } != -1) {
                outputStream.write(bytes, 0, read)
            }
            outputStream.flush()
            true
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            false
        } catch (e: IOException) {
            e.printStackTrace()
            false
        } finally {
            try {
                outputStream!!.close()
                inputStream!!.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

}