package theorycrafter.storage

import theorycrafter.esi.EveSsoTokens
import theorycrafter.utils.StoredCollection
import java.io.DataInput
import java.io.DataOutput


/**
 * Reads an EVE item id.
 */
fun DataInput.readEveId() = readInt()


/**
 * Reads an optional EVE item id.
 */
fun DataInput.readOptionalEveId(): Int? {
    val isPresent = readBoolean()
    return if (isPresent) readEveId() else null
}


/**
 * Writes an EVE item id.
 */
fun DataOutput.writeEveId(itemId: Int) = writeInt(itemId)


/**
 * Writes an optional EVE item id.
 */
fun DataOutput.writeOptionalEveId(itemId: Int?) {
    writeBoolean(itemId != null)
    if (itemId != null)
        writeEveId(itemId)
}


/**
 * Reads an optional [Int].
 */
fun DataInput.readOptionalInt(): Int? {
    val isPresent = readBoolean()
    return if (isPresent) readInt() else null
}


/**
 * Writes an optional [Int].
 */
fun DataOutput.writeOptionalInt(value: Int?) {
    writeBoolean(value != null)
    if (value != null)
        writeInt(value)
}


/**
 * Reads an optional security status value.
 */
fun DataInput.readOptionalSecurityStatus(): Float? = readFloat().let { if (it.isNaN()) null else it }


/**
 * Writes an optional security status value.
 */
fun DataOutput.writeOptionalSecurityStatus(value: Float?){
    writeFloat(value ?: Float.NaN)
}


/**
 * The serializer for [EveSsoTokens].
 */
object EveSsoTokensSerializer: StoredCollection.Serializer<EveSsoTokens> {


    override val itemFormatVersion = 2


    override fun readItem(input: DataInput, formatVersion: Int): EveSsoTokens {
        val accessToken = input.readUTF()
        val expirationUtcMillis = input.readLong()
        val refreshToken = input.readUTF()
        val tokenRefreshedUtcMillis = if (formatVersion >= 2) input.readLong() else 0

        return EveSsoTokens(
            accessToken = accessToken,
            expirationUtcMillis = expirationUtcMillis,
            refreshToken = refreshToken,
            lastRefreshedUtcMillis = tokenRefreshedUtcMillis
        )
    }


    override fun writeItem(output: DataOutput, item: EveSsoTokens) {
        output.writeUTF(item.accessToken)
        output.writeLong(item.expirationUtcMillis)
        output.writeUTF(item.refreshToken)
        output.writeLong(item.lastRefreshedUtcMillis)
    }


}