package de.mm20.launcher2.files.settings

import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.encodeToStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

@Serializable
data class FileSearchSettingsData(
    val localFiles: Boolean = true,
    val gdriveFiles: Boolean = false,
    val nextcloudFiles: Boolean = false,
    val owncloudFiles: Boolean = false,
    val plugins: Set<String> = emptySet(),
    val schemaVersion: Int = 1,
)

internal object FileSearchSettingsDataSerializer : Serializer<FileSearchSettingsData> {

    internal val json = Json {
        ignoreUnknownKeys = true
        encodeDefaults = true
    }

    override val defaultValue: FileSearchSettingsData
        get() = FileSearchSettingsData(schemaVersion = 0)

    override suspend fun readFrom(input: InputStream): FileSearchSettingsData {
        try {
            return json.decodeFromStream(input)
        } catch (e: IllegalArgumentException) {
            throw (CorruptionException("Cannot read json.", e))
        } catch (e: SerializationException) {
            throw (CorruptionException("Cannot read json.", e))
        } catch (e: IOException) {
            throw (CorruptionException("Cannot read json.", e))
        }
    }

    override suspend fun writeTo(t: FileSearchSettingsData, output: OutputStream) {
        json.encodeToStream(t, output)
    }
}