package com.hgsoft.log

import com.safframework.log.printer.file.name.FileNameGenerator
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicLong


/**
 *
 * <p>用途：</p>
 *
 * @author  yinxueqin@rd.hgits.cn
 * 创建时间: 2022/7/19 14:45
 * @author  更新者：
 * 更新时间:
 * 更新说明：
 * @since   1.0
 *
 */
class MTAFileNameGenerator(val prefix: String, val length: Long = 0)  : FileNameGenerator {

    private val mLocalDateFormat: ThreadLocal<SimpleDateFormat> = object : ThreadLocal<SimpleDateFormat>() {

        override fun initialValue() = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
    }

    private val counter = AtomicLong(0)

    override fun isFileNameChangeable() = true

    override fun generateFileName(logLevel: Int, tag: String, timestamp: Long, lastFileName: String): String {
        val sdf = mLocalDateFormat.get()?:SimpleDateFormat("yyyyMMdd", Locale.CHINA)
        val newFileNameDate =  sdf.let {
            it.timeZone = TimeZone.getDefault()
            it.format(Date(timestamp))
        }
        if (lastFileName.isNotEmpty()) {
            val file = File(lastFileName)
            if (!file.exists()) {
                val newFileName = prefix + "_" + newFileNameDate + "_" + counter.incrementAndGet() + ".xlog.log"
                return getNewFileName(newFileName, newFileNameDate)
            }
            val lastFileNameDate = file.name.replace(".", "_").split("_")[2]
            return if (newFileNameDate != lastFileNameDate) {
                prefix + "_" + newFileNameDate + ".xlog.log"
            } else {
                if (file.length() < length || length == 0L) {
                    lastFileName
                } else {
                    val newFileName = if (counter.get() > 1) {
                        prefix + "_" + newFileNameDate + "_" + counter.incrementAndGet() + ".xlog.log"
                    } else {
                        prefix + "_" + newFileNameDate + ".xlog.log"
                    }
                    getNewFileName(newFileName, newFileNameDate)
                }
            }
        } else {
            val newFileName = if (counter.get() > 1) {
                prefix + "_" + newFileNameDate + "_" + counter.incrementAndGet() + ".xlog.log"
            } else {
                prefix + "_" + newFileNameDate + ".xlog.log"
            }
            return getNewFileName(newFileName, newFileNameDate)
        }
    }

    private fun getNewFileName(newFileName: String, timeInfo: String): String {
        var tempNewFileName = newFileName
        val file = File(tempNewFileName)
        return if (file.exists()) {
            if (file.length() < length || length == 0L) {
                tempNewFileName
            } else {
                tempNewFileName = prefix + "_" + timeInfo + "_" + counter.incrementAndGet() + ".xlog.log"
                getNewFileName(tempNewFileName, timeInfo)
            }
        } else {
            tempNewFileName
        }
    }
}