package com.iscs.bozzys.utils

import android.app.Application
import android.util.Log
import com.iscs.bozzys.utils.DateUtil.format
import java.io.File

/**
 * 日志输出工具，后续这里输出日志到文件中
 */
object LogUtil {

    private const val TAG = "BozzysLogs"

    var showLog = true

    // 日志文件目录
    private const val DIR_NAME = "logs"

    // 限制最大日志占用空间，单位MB
    private const val MAX_FILE_SIZE = 10 * 1024 * 1024

    // 日志写锁保护
    private val syncLock = Any()

    private lateinit var app: Application

    /**
     * 日志工具初始化
     */
    fun init(app: Application) {
        this.app = app
    }

    /**
     * INFO级别日志输出
     */
    fun i(tag: String, msg: String) {
        if (showLog) Log.i("$TAG $tag", msg)
    }

    /**
     * DEBUG级别日志输出
     */
    fun d(tag: String, msg: String) {
        if (showLog) Log.d("$TAG $tag", msg)
    }

    /**
     * WARNING级别日志输出
     */
    fun w(tag: String, msg: String) {
        if (showLog) Log.w("$TAG $tag", msg)
    }

    /**
     * ERROR级别日志输出
     */
    fun e(tag: String, msg: String) {
        write("$TAG $tag", msg)
        if (showLog) Log.e("$TAG $tag", msg)
    }

    /**
     * 写日志到本地文件中
     *
     * @param tag   写入的标记
     * @param msg   写入的数据
     */
    private fun write(tag: String, msg: String) {
        val time = System.currentTimeMillis().format("yyyy-MM-dd HH:mm:ss.SSS")
        val line = "$time [$tag] $msg\n"
        synchronized(syncLock) {
            try {
                val dir = app.getExternalFilesDir(DIR_NAME) ?: return
                if (!dir.exists()) dir.mkdirs()

                val file = File(dir, "log_${System.currentTimeMillis().format("yyyyMMdd")}.txt")
                rotateIfNeed(file)

                file.appendText(line)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 超出大小后做文件备份处理
     *
     * @param file
     */
    private fun rotateIfNeed(file: File) {
        if (file.exists() && file.length() > MAX_FILE_SIZE) {
            val bak = File(file.parent, file.name + ".bak")
            file.renameTo(bak)
        }
    }

}