package co.id.datacomsolusindo.ipphonebridge

import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.commons.io.IOUtils
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
import java.util.HashMap
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@RestController
class BridgeRestController {
//    @PostMapping("/_response/{id}")
//    fun responseFromRest(@PathVariable("id") id: String, req: HttpServletRequest): String {
//        val objectMapper = ObjectMapper()
//        val typeRef: TypeReference<HashMap<String, Array<String>>> =
//            object : TypeReference<HashMap<String, Array<String>>>() {}
//        val body = IOUtils.toByteArray(req.getPart("body").inputStream)
//        Singletons.responseQue.getOrPut(id) {
//            Resp(
//                body,
//                String(IOUtils.toByteArray(req.getPart("status").inputStream)).toInt(),
//                if (req.getPart("header") != null) {
//                    objectMapper.readValue(String(IOUtils.toByteArray(req.getPart("header").inputStream)), typeRef)
//                } else {
//                    null
//                }
//            )
//        }
//
//        return "{\"success\":true}"
//    }
//
//    @GetMapping("/_request/{id}")
//    fun getResponseObj(@PathVariable("id") id: String): RequestBuilder {
//        if (Singletons.requestInstance.getOrElse(id) { null } == null) {
//            throw Exception("not found")
//        }
//        val rb = Singletons.requestInstance.getOrElse(id) { null }?.requestBuilder
//        if (rb == null) {
//            throw Exception("not found")
//        } else {
//            return rb
//        }
//    }

    private val logSetting = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<Configuration status=\"INFO\" name=\"MyApp\" packages=\"\">\n" +
            "    <Properties>\n" +
            "        <Property name=\"LOG_PATTERN\">%d %p [%c{1}] %m%n</Property>\n" +
            "        <Property name=\"APP_LOG_ROOT\">log</Property>\n" +
            "    </Properties>\n" +
            "\n" +
            "    <Appenders>\n" +
            "        <Console name=\"Console\" target=\"SYSTEM_OUT\" follow=\"true\">\n" +
            "            <PatternLayout pattern=\"\${LOG_PATTERN}\"/>\n" +
            "        </Console>\n" +
            "\n" +
            "        <RollingFile name=\"RollingFile\" fileName=\"\${APP_LOG_ROOT}/app/app.log\"\n" +
            "                     filePattern=\"\${APP_LOG_ROOT}/app/\$\${date:yyyy - MM}/app-%d{yyyy-MM-dd}-%i.log.zip\">\n" +
            "            <PatternLayout>\n" +
            "                <Pattern>\${LOG_PATTERN}</Pattern>\n" +
            "            </PatternLayout>\n" +
            "            <LevelRangeFilter minLevel=\"INFO\" maxLevel=\"INFO\" onMatch=\"ACCEPT\" onMismatch=\"DENY\"/>\n" +
            "            <Policies>\n" +
            "                <TimeBasedTriggeringPolicy/>\n" +
            "                <SizeBasedTriggeringPolicy size=\"10 MB\"/>\n" +
            "            </Policies>\n" +
            "        </RollingFile>\n" +
            "\n" +
            "        <RollingFile name=\"RollingFileError\" fileName=\"\${APP_LOG_ROOT}/error/app-error.log\"\n" +
            "                     filePattern=\"\${APP_LOG_ROOT}/error/\$\${date:yyyy - MM}/app-error-%d{yyyy-MM-dd}-%i.log.zip\">\n" +
            "            <PatternLayout>\n" +
            "                <Pattern>\${LOG_PATTERN}</Pattern>\n" +
            "            </PatternLayout>\n" +
            "            <LevelRangeFilter minLevel=\"FATAL\" maxLevel=\"WARN\" onMatch=\"ACCEPT\" onMismatch=\"DENY\"/>\n" +
            "            <Policies>\n" +
            "                <TimeBasedTriggeringPolicy/>\n" +
            "                <SizeBasedTriggeringPolicy size=\"10 MB\"/>\n" +
            "            </Policies>\n" +
            "        </RollingFile>        \n" +
            "        [CLIENT-APPENDER]\n" +
            "    </Appenders>\n" +
            "    <Loggers>\n" +
            "        <Root level=\"INFO\">\n" +
            "            <AppenderRef ref=\"Console\"/>\n" +
            "            <AppenderRef ref=\"RollingFile\"/>\n" +
            "            <AppenderRef ref=\"RollingFileError\"/>\n" +
            "        </Root>\n" +
            "        <Logger name=\"co.id.datacomsolusindo.ipphonebridge\" additivity=\"false\" level=\"INFO\">\n" +
            "            <AppenderRef ref=\"RollingFile\"/>\n" +
            "            <AppenderRef ref=\"Console\"/>\n" +
            "        </Logger>\n" +
            "        [CLIENT-LOGGER]               \n" +
            "    </Loggers>\n" +
            "</Configuration>"

    @GetMapping("/log-setting.xml", produces = [MediaType.APPLICATION_XML_VALUE])
    fun getLogSetting(servletResponse: HttpServletResponse): String {
        val appender = ClientHolder.get().entries.joinToString {
            "<RollingFile name=\"ClientAct${it.value.number}\" fileName=\"\${APP_LOG_ROOT}/client/${it.value.number}/act.log\"\n" +
                    "                     filePattern=\"\${APP_LOG_ROOT}/client/${it.value.number}/\$\${date:yyyy - MM}/act-%d{yyyy-MM-dd}-%i.log.zip\">\n" +
                    "            <PatternLayout>\n" +
                    "                <Pattern>\${LOG_PATTERN}</Pattern>\n" +
                    "            </PatternLayout>\n" +
                    "            <LevelRangeFilter minLevel=\"INFO\" maxLevel=\"INFO\" onMatch=\"ACCEPT\" onMismatch=\"DENY\"/>\n" +
                    "            <Policies>\n" +
                    "                <TimeBasedTriggeringPolicy/>\n" +
                    "                <SizeBasedTriggeringPolicy size=\"10 MB\"/>\n" +
                    "            </Policies>\n" +
                    "        </RollingFile>"

        }
        val logger = ClientHolder.get().entries.joinToString {
            "<Logger name=\"client-${it.value.number}\" additivity=\"false\" level=\"INFO\">\n" +
                    "            <AppenderRef ref=\"ClientAct${it.value.number}\"/>\n" +
                    "            <AppenderRef ref=\"Console\"/>\n" +
                    "        </Logger> "
        }

        return logSetting.replace("[CLIENT-APPENDER]", appender).replace("[CLIENT-LOGGER]", logger)
    }

    @GetMapping("/clientStat")
    fun getClientData(): Map<String, Client> {
        return ClientHolder.get()
    }

    @GetMapping("/clientStat/{id}")
    fun getClientDataOne(@PathVariable("id") id: String): Client? {
        return ClientHolder.get()[id]
    }
}