package com.mogo.cloud.tanlu.utils

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.os.Environment
import androidx.annotation.Keep
import java.io.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author lixiaopeng
 * @description 文件处理类
 * @since 2021/1/26
 */
@Keep
fun deletePicFile(filePath: String?): Boolean {
    val file = File(filePath)
    if (file.exists()) {
        //如果图片地址包含此路径则是C上面的拍照，需要再删除后摄图片
        if (filePath!!.contains("usbotg-1-1.1")) {
            //将地址替换成后摄图片地址
            val backFile =
                File(filePath.replace("frontPic", "backPic").replace("PhotoFront", "PhotoBack"))
            if (backFile.exists()) {
                return backFile.delete()
            }
            return file.delete()
        } else
            return file.delete()
    }
    return false
}

//删除某个目录下所有文件
fun deleteAllFile(file: File?) { //判断文件不为null或文件目录存在
    if (file == null || !file.exists()) {
        return
    }
    //取得这个目录下的所有子文件对象
    val files: Array<File> = file.listFiles()
    //遍历该目录下的文件对象
    for (f in files) {
        //判断子目录是否存在子目录,如果是文件则删除
        if (f.isDirectory) {
            deleteAllFile(f)
        } else {
            f.delete()
        }
    }
    //删除空文件夹  for循环已经把上一层节点的目录清空。
//    file.delete()
}


//根据本地视频文件生成缩略图文件
fun getVideoThumbnail(filePath: String, picPath: String): Boolean {
    var b: Bitmap? = null
    val retriever = MediaMetadataRetriever()
    try {
        retriever.setDataSource(filePath)
        b = retriever.getFrameAtTime(0)
    } catch (e: IllegalArgumentException) {
        e.printStackTrace()
    } catch (e: RuntimeException) {
        e.printStackTrace()
    } finally {
        try {
            retriever.release()
        } catch (e: RuntimeException) {
            e.printStackTrace()
        }
    }
    return bitmapToFile(b, picPath)
}

//bitmap转为file
fun bitmapToFile(bitmap: Bitmap?, filePath: String): Boolean {
    val baos = ByteArrayOutputStream()
    bitmap?.compress(Bitmap.CompressFormat.JPEG, 50, baos)
    val file = File(filePath)
    try {
        if (file.exists())
            file.delete()
        file.createNewFile()
        val fos = FileOutputStream(file)
        val ins = ByteArrayInputStream(baos.toByteArray())
        var x = 0
        val b = ByteArray(1024 * 100)
        while ({ x = ins.read(b);x }() != -1) {
            fos.write(b, 0, x)
        }
        fos.close()
        bitmap?.recycle()
    } catch (e: Exception) {
        e.printStackTrace()
        return false
    }

    return true
}

@Keep
fun getVideoPicPath(): String {
    val moviesDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES
    )
    moviesDir.mkdirs()

    val builder = StringBuilder()
    builder.append("pic_")
            .append(SimpleDateFormat("yyyyMMddHHmmss").format(Date()))
    val filePrefix = builder.toString()
    val fileExtn = ".jpg"
    var destPath = File(moviesDir, filePrefix + fileExtn)

    var fileNo = 0
    while (destPath.exists()) {
        fileNo++
        destPath = File(moviesDir, filePrefix + fileNo + fileExtn)
    }

    return destPath.absolutePath
}


//获取压缩后的视频路径 /storage/emulated/0/Movies/compress_video_20210126174432.mp4
@Keep
fun getCompressVideoPath(): String {
    val moviesDir = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_MOVIES
    )
    moviesDir.mkdirs()

    val builder = StringBuilder()
    builder.append("compress_video_")
        .append(SimpleDateFormat("yyyyMMddHHmmss").format(Date()))
    val filePrefix = builder.toString()
    val fileExtn = ".mp4"
    var destPath = File(moviesDir, filePrefix + fileExtn)

    var fileNo = 0
    while (destPath.exists()) {
        fileNo++
        destPath = File(moviesDir, filePrefix + fileNo + fileExtn)
    }

    return destPath.absolutePath
}

