package com.grkj.iscs.util.log

import android.os.Handler
import android.os.Looper
import android.os.Message

import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

import kotlin.Throws

/**
 * 功能描述：日志写入类
 */
class LogWriteHandler(
    looper: Looper?, //日志存储路径
    private val folder: String, //单个日志最大占用内存
    private val maxFileSize: Int
) : Handler(looper!!) {
    private val sdfTime = SimpleDateFormat("yyyy-MM-dd")
    override fun handleMessage(msg: Message) {
        val content = msg.obj as String
        var fileWriter: FileWriter? = null
        val logFile = getLogFile(folder, "logs")
        try {
            fileWriter = FileWriter(logFile, true)
            writeLog(fileWriter, content)
            fileWriter.flush()
            fileWriter.close()
        } catch (e: IOException) {
            handleException(fileWriter)
        }
    }

    private fun handleException(fileWriter: FileWriter?) {
        if (fileWriter == null) return
        try {
            fileWriter.flush()
            fileWriter.close()
        } catch (e1: IOException) {
            e1.printStackTrace()
        }
    }

    /**
     * This is always called on a single background thread.
     * Implementing classes must ONLY write to the fileWriter and nothing more.
     * The abstract class takes care of everything else including close the stream and catching IOException
     *
     * @param fileWriter an instance of FileWriter already initialised to the correct file
     */
    @Throws(IOException::class)
    private fun writeLog(fileWriter: FileWriter, content: String) {
        fileWriter.append(content)
    }

    private fun getLogFile(folderName: String, fileName: String): File {
        var folderName = folderName
        var fileName = fileName
        folderName = "$folderName/$time"
        fileName = "$fileName-$time"
        val folder = File(folderName)
        if (!folder.exists()) folder.mkdirs()
        var newFileCount = 0
        var existingFile: File? = null
        var newFile = File(folder, String.format("%s-%s.txt", fileName, newFileCount))
        while (newFile.exists()) {
            existingFile = newFile
            newFileCount++
            newFile = File(folder, String.format("%s-%s.txt", fileName, newFileCount))
        }
        if (existingFile == null) return newFile
        return if (existingFile.length() >= maxFileSize) newFile else existingFile
    }

    private val time: String
        private get() = sdfTime.format(Date())
}