package co.id.datacomsolusindo.ipphonebridge

import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.core.config.Configurator
import org.ini4j.Wini
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.messaging.simp.stomp.StompHeaderAccessor
import org.springframework.messaging.support.GenericMessage
import org.springframework.stereotype.Component
import org.springframework.web.socket.messaging.SessionConnectEvent
import org.springframework.web.socket.messaging.SessionDisconnectEvent
import org.springframework.web.socket.messaging.SessionSubscribeEvent
import java.io.File
import java.net.URI
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Component
class WebSocketEventListener {
    @EventListener(ApplicationReadyEvent::class)
    fun doSomethingAfterStartup() {
        val yourFile = File("health")
        yourFile.createNewFile()
        println("file created")
        println(yourFile.path)
        println(yourFile.name)
        logBuilder()
    }

    fun logBuilder() {
        Configurator.reconfigure(URI("http://127.0.0.1:${Singletons.properties()["server.port"]}/log-setting.xml"))
    }

    @EventListener
    fun onConnect(event: SessionConnectEvent) {
        val accessor = StompHeaderAccessor.wrap(event.message)
        val sessionId = accessor.sessionId
        AppLog.write(this.javaClass).info("connect with session id $sessionId")

    }

    @EventListener
    fun onDisconnect(event: SessionDisconnectEvent) {
        AppLog.write(this.javaClass).info("disconnect with session id ${event.sessionId}")
        ClientHolder.removeBySessionId(event.sessionId)
    }

    @EventListener
    fun handleSessionSubscribeEvent(event: SessionSubscribeEvent) {
        val message = event.message as GenericMessage<*>
        val simDestination = message.headers["simpDestination"] as String?
        val accessor = StompHeaderAccessor.wrap(event.message)
        val sessionId = accessor.sessionId
        AppLog.write(this.javaClass).info("subscribe to $simDestination with session id $sessionId")


        if (!(simDestination!!.startsWith("/topic/healthCheck") || simDestination.startsWith("/topic/notification"))) {
            // do stuff
            val clNum = simDestination.split("/")[3]
            ClientHolder.put(
                clNum, Client(
                    clNum,
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")),
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")),
                    sessionId
                )
            )

            LogManager.getLogger(this.javaClass).info("clientConnected $simDestination")
            logBuilder()
            LogManager.getLogger("client-$clNum").info("Client $clNum Connected")
        }
    }
}