package de.storchp.fdroidbuildstatus.adapter.fdroid

import com.google.gson.*
import com.google.gson.annotations.JsonAdapter
import java.lang.reflect.Type
import java.util.*

@JsonAdapter(MissingBuilds.Deserializer::class)
class MissingBuilds {
    private val missingBuildItems: MutableSet<MissingBuildItem?> = HashSet()
    fun getFailedBuildItems(): Set<MissingBuildItem?> {
        return missingBuildItems
    }

    class Deserializer : JsonDeserializer<MissingBuilds?> {
        override fun deserialize(
            json: JsonElement,
            typeOfT: Type,
            context: JsonDeserializationContext
        ): MissingBuilds? {
            return try {
                val missingBuilds = MissingBuilds()
                if (json.isJsonObject) {
                    val jsonObject = json.asJsonObject
                    missingBuilds.missingBuildItems.addAll(jsonObject.entrySet()
                        .mapNotNull { (key, element): Map.Entry<String?, JsonElement> ->
                            if (element.isJsonArray && element.asJsonArray.size() > 0) {
                                return@mapNotNull MissingBuildItem(
                                    key!!,
                                    element.asJsonArray[0].asLong
                                )
                            }
                            null
                        }
                        .toList())
                }
                missingBuilds
            } catch (_: Exception) {
                null
            }
        }
    }
}