// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.settings.feeds

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.github.jershell.kbson.KBson
import kotlinx.serialization.Serializable
import xyz.apiote.bimba.czwek.api.Server
import java.net.URLEncoder

@Serializable
@OptIn(ExperimentalStdlibApi::class)
data class FeedsSettings(val settings: MutableMap<String, FeedSettings>) {
	fun activeFeedsCount() = settings.count { it.value.enabled && it.value.useOnline }
	fun activeFeeds() = settings.filter { it.value.enabled && it.value.useOnline }.keys
	fun getIDs() = activeFeeds().filter { it != "transitous" }.joinToString(",")
	fun transitousEnabled() = activeFeeds().contains("transitous")
	fun bimbaEnabled() = activeFeeds().filter { it != "transitous" }.isNotEmpty()

	fun save(context: Context, server: Server) {
		val doc = KBson().dump(serializer(), this).toHexString()
		val feedsPreferences =
			context.getSharedPreferences(PREFERENCES_NAME, AppCompatActivity.MODE_PRIVATE)
		feedsPreferences.edit {
			val key = URLEncoder.encode(server.apiPath, "utf-8")
			putString(key, doc)
		}
	}

	companion object {
		const val PREFERENCES_NAME = "feeds_settings"
		fun load(context: Context, apiPath: String = Server.get(context).apiPath): FeedsSettings {
			val doc = context.getSharedPreferences(
				PREFERENCES_NAME,
				Context.MODE_PRIVATE
			).getString(URLEncoder.encode(apiPath, "utf-8"), null)
			return doc?.let { KBson().load(serializer(), doc.hexToByteArray()) } ?: FeedsSettings(
				mutableMapOf()
			)
		}
	}
}

@Serializable
data class FeedSettings(
	val enabled: Boolean,
	val useOnline: Boolean
)

fun migrateFeedsSettings(context: Context, server: Server = Server.get(context)) {
	val shp =
		context.getSharedPreferences(
			URLEncoder.encode(server.apiPath, "utf-8"),
			AppCompatActivity.MODE_PRIVATE
		)
	if (shp.all.isEmpty()) {
		return
	}

	val feedsSettings = FeedsSettings(mutableMapOf())
	shp.all.forEach { (feedID, enabled) ->
		if (enabled as Boolean) {
			feedsSettings.settings[feedID] = FeedSettings(enabled = true, useOnline = true)
		}
	}
	shp.edit {
		clear()
	}
	feedsSettings.save(context, server)
}
