package com.quyunshuo.androidbaseframemvvm.common.util

import android.text.TextUtils
import android.util.Log
import com.elvishew.xlog.printer.file.naming.FileNameGenerator
import com.quyunshuo.androidbaseframemvvm.common.util.FileUtil.makeFilePath

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.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.Random
import java.util.TimeZone

class CustomFileNameGenerator : FileNameGenerator {
    override fun isFileNameChangeable(): Boolean {
        return false
    }

    var mLocalDateFormat: ThreadLocal<SimpleDateFormat> = object : ThreadLocal<SimpleDateFormat>() {
        override fun initialValue(): SimpleDateFormat {
            return SimpleDateFormat("yyyyMMdd", Locale.US)
        }
    }

    override fun generateFileName(logLevel: Int, timestamp: Long): String {
        val sdf = mLocalDateFormat.get()
        sdf.timeZone = TimeZone.getDefault()
        return sdf.format(Date(timestamp)) + "-" + getDeviceId()+".txt"
    }

    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
    }

    //读取指定目录下的所有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
    }

    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")
        }
    }
}
