package gaf3.core.jpa

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import javax.persistence.Column
import javax.persistence.Embeddable
import javax.persistence.PrePersist


@Embeddable
@JsonSerialize(using = GafOrderNum.Serializer::class)
@JsonDeserialize(using = GafOrderNum.Deserializer::class)
class GafOrderNum {

    @JvmOverloads
    constructor(value: Int? = null) {
        this.value = value
    }

    constructor(value: String) {
        this.value = value.toInt()
    }

    @Column(name = "ORDER_NUM")
    var value: Int? = null

    @PrePersist
    fun insertOrder() {
        if (value == null) value = 0
    }

    operator fun plusAssign(other: Int?) {
        this.value = other
    }


    class Serializer : JsonSerializer<GafOrderNum?>() {
        @Throws(JsonProcessingException::class)
        override fun serialize(num: GafOrderNum?, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider) {
            jsonGenerator.writeNumber(num?.value ?: 0)
        }
    }

    class Deserializer : JsonDeserializer<GafOrderNum?>() {
        @Throws(JsonProcessingException::class)
        override fun deserialize(jsonParser: JsonParser?, deserializationContext: DeserializationContext?): GafOrderNum? {
            return try {
                jsonParser?.let { GafOrderNum(it.intValue) }
            } catch (e: Exception) {
                throw RuntimeException(e)
            }
        }
    }
}

