package com.bc_chat.bc_base.utils

import android.graphics.Bitmap
import android.os.Environment
import java.io.*

/**
 * author：Created by zhaohaoting on 2019/2/22
 * email：526309416@qq.com
 * desc：本地缓存有关
 */
object CacheUtils {
    /**
     * 生成相册的图片文件路径
     */
    private val picDir = Environment.getExternalStorageDirectory().absolutePath + File.separator + "bc_chat/picture/"


    /**
     * 直接保存到相册文件夹
     */
    fun savePictureAlbum(bitmap: Bitmap, fileName: String): File? {
        val file = File(picDir, fileName)
        if (!file.exists()) {
            val parentFile = file.parentFile
            if (!parentFile.exists()) {
                parentFile.mkdirs()
            }
        } else {
            file.delete()
        }
        try {
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
            return file
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 复制到相册文件夹
     */
    fun copyPictureAlbum(originalPath: String, fileName: String): File? {
        val file = File(picDir, fileName)
        var fileInputStream: FileInputStream? = null
        var fileOutputStream: FileOutputStream? = null
        if (!file.exists()) {
            val parentFile = file.parentFile
            if (!parentFile.exists()) {
                parentFile.mkdirs()
            }
        } else {
            file.delete()
        }
        try {
            fileInputStream = FileInputStream(File(originalPath))
            fileOutputStream = FileOutputStream(file)
            val buf = ByteArray(1024)
            var len = 0
            while (fileInputStream.read(buf).also { len = it } != -1) {
                fileOutputStream.write(buf, 0, len)
                fileOutputStream.flush()
            }
            return file
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            fileInputStream?.close()
            fileOutputStream?.close()
        }
        return null
    }

    fun isHaveFilePic(fileName: String): File? {
        val file = File(picDir, fileName)
        return if (file.exists()) {
            file
        } else null
    }
}
