package com.quyunshuo.androidbaseframemvvm.common.util

import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Log
import com.quyunshuo.androidbaseframemvvm.common.constant.SavaAddress
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStreamReader
import java.io.RandomAccessFile
import java.net.URLConnection
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Random

/**
 * 文件工具类
 */
object FileUtil {
    var FILEPATH: String = SavaAddress.log
    val SEVENT_DAYS: Long = 604800000
    var FILEPATH_PHONE: String = SavaAddress.savePhone



    /**
     * 获取指定目录内所有文件路径
     *
     * @param dirPath 需要查询的文件目录
     * @param _type   查询类型，比如mp3什么的
     */
    fun getAllFiles(dirPath: String?, _type: String?): Array<File>? {
        val f = File(dirPath)
        if (!f.exists()) { //判断路径是否存在
            if (f.mkdir()) {
                //todo 会出现栈溢出【为什么要加上这一句本身就没有意义。】
                getAllFiles(dirPath, _type)
            }
            return null
        }
        val files = f.listFiles()
            ?: //判断权限
            return null
        for (_file in files) { //遍历目录
            val _name = _file.name
            val filePath = _file.absolutePath //获取文件路径
            val fileName = _file.name.substring(0, _name.length - 4) //获取文件名
            LogUtil.d("LOGCAT", "fileName:$fileName")
            LogUtil.d("LOGCAT", "filePath:$filePath")
        }

        return files
    }

    /**
     * 判断文件是否为图片
     *
     * @param filePath 路径
     * @return
     */
    fun isImageFile(filePath: String?): Boolean {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filePath, options)
        if (options.outWidth == -1) {
            return false
        }
        return true
    }


    private val PREFIX_VIDEO = "video/"

    /**
     * Get the Mime Type from a File
     *
     * @param fileName 文件名
     * @return 返回MIME类型
     * thx https://www.oschina.net/question/571282_223549
     * add by fengwenhua 2017年5月3日09:55:01
     */
    private fun getMimeType(fileName: String): String {
        val fileNameMap = URLConnection.getFileNameMap()
        val type = fileNameMap.getContentTypeFor(fileName)
        return type
    }

    /**
     * 根据文件后缀名判断 文件是否是视频文件
     *
     * @param fileName 文件名
     * @return 是否是视频文件
     */
    fun isVedioFile(fileName: String): Boolean {
        val mimeType = getMimeType(fileName)
        if (!TextUtils.isEmpty(fileName) && mimeType.contains(PREFIX_VIDEO)) {
            return true
        }
        return false
    }


//    fun getDeviceId(): String {
//        var deviceId = ""
//        val file = File("/storage/emulated/0/mht/deviceid.txt")
//        val fileContent = getFileContent(file)
//        if (file != null && !TextUtils.isEmpty(fileContent)) {
//            //如果存在 直接获取
//            deviceId = fileContent.trim { it <= ' ' }
//        } else {
//            //不存在 先生成再获取
//            writeData()
//            deviceId = getFileContent(file).trim { it <= ' ' }
//        }
//        val param = SharedPreferencesUtils.getParam(Name.CONNECT_STATE, 10) as Int
//        return if (param == 2) {
//            deviceId
//        } else {
//            ""
//        }
//    }

    fun getDeviceId(): String {
        var deviceId = ""
        val file = File("/storage/emulated/0/mht/deviceid.txt")
        val fileContent = getFileContent(file)
        if (file != null && !TextUtils.isEmpty(fileContent)) {
            //如果存在 直接获取

            deviceId = fileContent.trim { it <= ' ' }
        } else {
            //不存在 先生成再获取
            writeData()
            deviceId = getFileContent(file).trim { it <= ' ' }
        }
        return deviceId
    }


    private fun writeData() {
        val filePath = "/storage/emulated/0/mht/"
        val fileName = "deviceid.txt"
        var deviceId = ""
        val l = System.currentTimeMillis()
        val random = Random()
        var randomText = ""
        for (i in 0..3) {
            val j = random.nextInt(1000)
            randomText = randomText + j
        }
        deviceId = l.toString() + randomText
        writeTxtToFile(deviceId, filePath, fileName)
    }


    // 将字符串写入到文本文件中
    private fun writeTxtToFile(strcontent: String, filePath: String, fileName: String) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName)

        val strFilePath = filePath + fileName
        // 每次写入时，都换行写
        val strContent = strcontent + "\r\n"
        try {
            val file = File(strFilePath)
            if (!file.exists()) {
                LogUtil.d("TestFile", "Create the file:$strFilePath")
                file.parentFile.mkdirs()
                file.createNewFile()
            }
            val raf = RandomAccessFile(file, "rwd")
            raf.seek(file.length())
            raf.write(strContent.toByteArray())
            raf.close()
        } catch (e: Exception) {
            Log.e("TestFile", "Error on write File:$e")
        }
    }


    //生成文件
    fun makeFilePath(filePath: String, fileName: String): File? {
        var file: File? = null
        makeRootDirectory(filePath)
        try {
            file = File(filePath + fileName)
            if (!file.exists()) {
                file.createNewFile()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return file
    }


    //生成文件夹
    fun makeRootDirectory(filePath: String?) {
        var file: File? = null
        try {
            file = File(filePath)
            if (!file.exists()) {
                file.mkdir()
            }
        } catch (e: Exception) {
            Log.i("error:", e.toString() + "")
        }
    }


    //读取指定目录下的所有TXT文件的文件内容
    private fun getFileContent(file: File?): String {
        var content = ""
        if (!file!!.isDirectory) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.name.endsWith("txt")) { //文件格式为""文件
                var buffreader: BufferedReader? = null
                try {
                    buffreader = BufferedReader(InputStreamReader(FileInputStream(file), "UTF-8"))
                    content += buffreader.readLine() + "\n"
                } catch (e: FileNotFoundException) {
                    LogUtil.d("TestFile", "The File doesn't not exist.")
                } catch (e: IOException) {
                } finally {
                    try {
                        buffreader?.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        }
        return content
    }


    //flie：要删除的文件夹的所在位置
    fun deleteFile(file: File) {
        if (file.isDirectory) {
            val files = file.listFiles()
            for (i in files.indices) {
                val f = files[i]
                deleteFile(f)
            }
            //            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete()
        }
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName
     * @return
     */
    fun getFileType(fileName: String): String {
        return fileName.substring(fileName.lastIndexOf(".") + 1)
    }

    /**
     * 删除超过7天的log文件
     */
    fun pastDueLog() {
        val logFolder = File(FILEPATH)
        if (logFolder.exists()) {
            val logFiles = logFolder.listFiles() ?: return
            for (file in logFiles) {
                val format = SimpleDateFormat("yyyyMMdd")
                val nowDate = format.format(Date(System.currentTimeMillis()))
                //LogUtil.d(TAG, "duibi: " + nowDate);
                try {
                    val replace = file.name.replace(
                        "-" + FileUtil.getDeviceId() + ".txt",
                        ""
                    )

                    if ("out.txt" == replace) {
                        continue
                    }
                    val dateFile = format.parse(replace)
                    val dataNow = format.parse(nowDate)
                    val fileTime = dateFile.time
                    val nowTime = dataNow.time
                    if (nowTime - fileTime > SEVENT_DAYS) {
                        //如果超过7天，我们就进行删除指定的文件，否则就什么都不做。
                        //LogUtil.d(TAG, "duibi: "+fileTime);
                        //删除
                        file.delete()
                    }
                    //LogUtil.d(TAG, "duibi: "+dataNow);
                    //LogUtil.d(TAG, "duibi: " + file.getName());
                } catch (e: ParseException) {
                    //604800000 7天
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    fun getFileName(): String {
        val format = SimpleDateFormat("yyyyMMdd")
        val date =
            format.format(Date(System.currentTimeMillis())) + "-" + getDeviceId() + ".txt"
        return date
    }

    /**
     * 創建log文件
     */
    fun createLogFile(): File? {
        return makeFilePath(FILEPATH, getFileName())
    }

    /**
     * 創建log文件
     */
    fun createPhoneFile(): File? {
        return makeFilePath(FILEPATH_PHONE, getFileName())
    }
}