package com.peterino.blastoise

import android.content.Context
import java.net.URI
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

object SessionStore {
    const val defaultServerBaseUrl = "https://tunes.peterino.com"
    private const val legacyDefaultServerBaseUrl = "http://mhsgroove.peterino.com:3001"
    const val userAgent = "BlastoiseAndroid/0.1"

    @Volatile
    var serverBaseUrl: String = defaultServerBaseUrl

    @Volatile
    var cookieHeader: String = ""

    @Volatile
    var themeKey: String = "seraph"

    fun load(context: Context) {
        val prefs = context.getSharedPreferences("blastoise", Context.MODE_PRIVATE)
        val storedBaseUrl = prefs.getString("serverBaseUrl", defaultServerBaseUrl).orEmpty().trim()
        serverBaseUrl = when {
            storedBaseUrl.isBlank() -> defaultServerBaseUrl
            storedBaseUrl.trimEnd('/') == legacyDefaultServerBaseUrl -> defaultServerBaseUrl
            else -> storedBaseUrl.trimEnd('/')
        }
        cookieHeader = prefs.getString("cookieHeader", "") ?: ""
        themeKey = prefs.getString("themeKey", "seraph") ?: "seraph"
    }

    fun save(context: Context) {
        context.getSharedPreferences("blastoise", Context.MODE_PRIVATE)
            .edit()
            .putString("serverBaseUrl", serverBaseUrl)
            .putString("cookieHeader", cookieHeader)
            .putString("themeKey", themeKey)
            .apply()
    }

    fun setBaseUrl(input: String) {
        val trimmed = input.trim().trimEnd('/')
        serverBaseUrl = when {
            trimmed.isEmpty() -> defaultServerBaseUrl
            trimmed.startsWith("http://") || trimmed.startsWith("https://") -> trimmed
            else -> "http://$trimmed"
        }
    }

    fun httpUrl(path: String): String {
        return serverBaseUrl.trimEnd('/') + path
    }

    fun wsUrl(channelId: String): String {
        val uri = URI(serverBaseUrl)
        val scheme = if (uri.scheme == "https") "wss" else "ws"
        val authority = uri.rawAuthority
        return "$scheme://$authority/api/channels/${encodePath(channelId)}/ws"
    }

    fun trackUrl(trackId: String): String {
        return httpUrl("/api/tracks/${encodePath(trackId)}")
    }

    private fun encodePath(value: String): String {
        return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()).replace("+", "%20")
    }
}
