package com.yidian.shenghuoquan.newscontent.utils

import android.content.Context
import android.net.Uri
import java.io.File
import java.io.FileOutputStream

/**
 * author: yinjiacheng
 * date: 5/31/21 4:29 PM
 * description: 文件相关操作
 */

object FileUtil {

  /**
   * 从Uri生成File
   * @param path 生成文件的全路径
   */
  fun generateFileFromUri(context: Context?, uri: Uri?, path: String) {
    if (uri != null) {
      val file = File(path)
      if (file.exists()) file.delete()
      if (file.parentFile?.exists() == false) file.parentFile?.mkdirs()
      file.createNewFile()
      val inputStream = context?.contentResolver?.openInputStream(uri)
      val outputStream = FileOutputStream(path)
      inputStream?.copyTo(outputStream)
      inputStream?.close()
      outputStream.close()
    }
  }

  /**
   * 从assets中复制文件到指定路径
   * @param assetFileName assets中文件名
   * @param destPath 目标路径
   */
  fun copyFileFromAssets(context: Context?, assetFileName: String, destPath: String) {
    val file = File(destPath)
    if (file.exists()) file.delete()
    if (file.parentFile?.exists() == false) file.parentFile?.mkdirs()
    file.createNewFile()
    val outputStream = FileOutputStream(file)
    context?.assets?.open(assetFileName)?.copyTo(outputStream)
    outputStream.close()
  }

  /**
   * 从String生成File
   * @param data 待写入的String
   * @param destPath 目标路径
   */
  fun generateFileFromString(data: String?, destPath: String) {
    if (data.isNullOrEmpty()) return
    val file = File(destPath)
    if (file.exists()) file.delete()
    if (file.parentFile?.exists() == false) file.parentFile?.mkdirs()
    file.createNewFile()
    File(destPath).writeText(data)
  }
}
