package de.walamana.plugins

import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.application.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import java.util.*

fun Application.configureSerialization() {
    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
            ignoreUnknownKeys = true
        })

    }

    routing {
        get("/json/kotlinx-serialization") {
            println("Test")
//            call.respond("Test")
            call.respond(mapOf("hello" to "world"))
        }
    }
}

typealias CommaSeperatedStringList = @Serializable(StringListAsCommaSeperatedString::class) List<String>;

object StringListAsCommaSeperatedString : KSerializer<List<String>> {
    override val descriptor: SerialDescriptor
            = PrimitiveSerialDescriptor("List<String>", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): List<String> {
        return decoder.decodeString().split(",")
    }

    override fun serialize(encoder: Encoder, value: List<String>) {
        encoder.encodeString(value.joinToString(","))
    }

}


typealias DateAsLong = @Serializable(DateAsLongSerializer::class) Date
object DateAsLongSerializer : KSerializer<Date> {
    override val descriptor: SerialDescriptor
            = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG)

    override fun serialize(encoder: Encoder, value: Date) {
        encoder.encodeLong(value.time)
    }

    override fun deserialize(decoder: Decoder): Date {
        return Date(decoder.decodeLong())
    }
}
