package net.taehui.twilight.system

import org.apache.logging.log4j.core.Core
import org.apache.logging.log4j.core.Layout
import org.apache.logging.log4j.core.LogEvent
import org.apache.logging.log4j.core.appender.AbstractAppender
import org.apache.logging.log4j.core.config.plugins.Plugin
import org.apache.logging.log4j.core.config.plugins.PluginAttribute
import org.apache.logging.log4j.core.config.plugins.PluginElement
import org.apache.logging.log4j.core.config.plugins.PluginFactory
import org.jline.reader.LineReader
import org.jline.reader.LineReaderBuilder
import org.jline.terminal.TerminalBuilder
import java.io.Serializable

@Plugin(name = "Window", category = Core.CATEGORY_NAME)
class Window(name: String, layout: Layout<out Serializable>) :
    AbstractAppender(name, null, layout, true, null) {
    val r: LineReader = LineReaderBuilder.builder().terminal(TerminalBuilder.builder().build()).build()

    init {
        r.setOpt(LineReader.Option.DISABLE_EVENT_EXPANSION)
        r.unsetOpt(LineReader.Option.INSERT_TAB)
    }

    override fun append(event: LogEvent) {
        r.printAbove(layout.toSerializable(event).toString())
    }

    companion object {
        lateinit var window: Window

        @JvmStatic
        @PluginFactory
        fun getWindow(
            @PluginAttribute("name") name: String,
            @PluginElement("Layout") layout: Layout<out Serializable>
        ): Window {
            window = Window(name, layout)
            return window
        }
    }
}