package ocelot.desktop.util

import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.config.Configurator
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory

import java.nio.file.Files

trait LoggingConfiguration {
  {
    val builder = ConfigurationBuilderFactory.newConfigurationBuilder()

    // Console appender
    val consoleAppender = builder.newAppender("console", "Console")

    var patternLayout = builder.newLayout("PatternLayout")
    patternLayout.addAttribute("pattern", "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n")
    consoleAppender.add(patternLayout)

    builder.add(consoleAppender)

    Files.createDirectories(OcelotPaths.desktopLog.getParent)

    // File
    val fileAppender = builder.newAppender("file", "File")
    fileAppender.addAttribute("fileName", OcelotPaths.desktopLog)
    fileAppender.addAttribute("immediateFlush", false)
    fileAppender.addAttribute("append", false)

    patternLayout = builder.newLayout("PatternLayout")
    patternLayout.addAttribute("pattern", "%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n")
    fileAppender.add(patternLayout)

    builder.add(fileAppender)

    // Root logger
    val rootLogger = builder.newRootLogger(Level.DEBUG)
    rootLogger.add(builder.newAppenderRef("console"))
    rootLogger.add(builder.newAppenderRef("file"))
    builder.add(rootLogger)

    // Webcam logger, required for Camera node from Computronix
    val webcamLogger = builder.newLogger("com.github.sarxos.webcam", Level.INFO)
    builder.add(webcamLogger)

    Configurator.initialize(builder.build)
  }
}
