package com.grkj.iscs.util.log

import android.content.Context
import android.util.Log
import java.io.File
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Collections

/**
 * Log工具类
 */
object LogUtil {
    //使用接口 避免耦合 后续若要更换日志打印框架 直接new 其它实现类即可
    private val log: ILog = LogHandle()

    // 是否打印代码行数
    private const val isPrintLine = false

    /**
     * 日志初始化
     *
     * @param path 日志文件路径
     */
    fun init(mContext: Context,path: String) {
        log.init(mContext,path)
        d("日志初始化成功!")
        clearOldFolder(path)
    }

    /**
     * debug日志
     *
     * @param str
     */
    fun d(str: String?) {
        log.d(Thread.currentThread().id.toString() + "  " + generateTag(), str)
        Log.d(generateTag(), str!!)
    }

    /**
     * info日志
     *
     * @param str
     */
    fun i(str: String?) {
        log.i(Thread.currentThread().id.toString() + "  " + generateTag(), str)
        Log.i(generateTag(), str!!)
    }

    /**
     * warn日志
     *
     * @param str
     */
    fun w(str: String?) {
        log.w(Thread.currentThread().id.toString() + "  " + generateTag(), str)
        Log.w(generateTag(), str!!)
    }

    /**
     * error日志
     *
     * @param str
     */
    @JvmStatic
    fun e(str: String?) {
        log.e(Thread.currentThread().id.toString() + "  " + generateTag(), str)
        Log.e(generateTag(), str!!)
    }

    /**
     * exception日志
     *
     * @param throwable
     */
    fun e(throwable: Throwable) {
        log.e(Thread.currentThread().id.toString() + "  " + generateTag(), throwable)
        Log.e(generateTag(), throwable.message.toString())
    }

    fun generateTag(): String {
        val caller = Thread.currentThread().stackTrace[4]
        var callerClazzName = caller.className
        callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1)
        var tag = "%s.%s"
        if (isPrintLine) {
            tag += "(Line:%d)"
            tag = String.format(tag, callerClazzName, caller.methodName, caller.lineNumber)
        } else {
            // 打印方法名
            tag = String.format(tag, callerClazzName, caller.methodName)

            // 不打印方法名
            // tag = "%s";
            // tag = String.format(tag, callerClazzName);
        }
        return tag
    }

    /**
     * 清理超过15天的日志
     *
     * @param folderPath 文件夹路径
     */
    private fun clearOldFolder(folderPath: String) {
        val list: List<String> = getAllFolderName(folderPath)
        // 日志文件夹只保留15天的
        if (list.size > 15) {
            deleteFirstFolder(list, folderPath)
        }
    }

    /**
     * 获取所有文件夹名称
     *
     * @param folderPath 文件夹路径
     * @return 文件夹名称集合
     */
    private fun getAllFolderName(folderPath: String): ArrayList<String> {
        val fileList = ArrayList<String>()
        val file = File(folderPath)
        val tempList = file.listFiles()
        tempList?.let {
            for (i in it.indices) {
                if (it[i].isDirectory) {
                    d("文件夹：" + it[i].name)
                    fileList.add(it[i].name)
                }
            }
        }
        return fileList
    }

    /**
     * 按日期排序删除最早的一个文件夹
     */
    private fun deleteFirstFolder(list: List<String>?, path: String) {
        if (list.isNullOrEmpty()) {
            e("deleteFirstFolder fail")
            return
        }
        // 先排序
        Collections.sort(list) { o1: String, o2: String ->
            // 按照时间进行降序排列
            val timeFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd") //日期格式
            try {
                val date0 = timeFormat.parse(o1)
                val date1 = timeFormat.parse(o2)
                if (date0.time > date1.time) {
                    return@sort 1
                }
                if (o1 === o2) {
                    return@sort 0
                }
            } catch (e: ParseException) {
                e("日期转换异常")
                e.printStackTrace()
            }
            -1
        }
        val dirPath = path + File.separator + list[0]
        e("dir path : $dirPath")
        val file = File(dirPath)
        if (file.exists() && file.isDirectory) {
            val childFiles = file.listFiles()
            if (childFiles == null || childFiles.size == 0) {
                file.delete()
            } else {
                for (i in childFiles.indices) {
                    childFiles[i].delete()
                }
                file.delete()
            }
        }
    }
}