package com.zaneschepke.wireguardautotunnel.client.domain.model

import com.zaneschepke.wireguardautotunnel.parser.Config
import kotlin.collections.get
import kotlinx.serialization.Serializable

@Serializable
data class TunnelConfig(
    val id: Long = 0,
    val name: String,
    val quickConfig: String,
    val active: Boolean = false,
    val position: Int = 0,
) {

    fun asConfig(): Config {
        return Config.parseQuickString(quickConfig)
    }

    companion object {

        const val DEFAULT_TUNNEL_NAME = "tunnel"

        val Empty = TunnelConfig(name = DEFAULT_TUNNEL_NAME, quickConfig = "")

        fun configFromQuick(quick: String): Config {
            return Config.parseQuickString(quick)
        }

        fun fromQuickString(quick: String, name: String? = null): TunnelConfig {
            val config = configFromQuick(quick)
            return tunnelConfFromConfig(config, name)
        }

        private fun tunnelConfFromConfig(config: Config, name: String? = null): TunnelConfig {
            return TunnelConfig(
                name = name ?: DEFAULT_TUNNEL_NAME,
                quickConfig = config.asQuickString(),
            )
        }

        private const val IPV6_ALL_NETWORKS = "::/0"
        private const val IPV4_ALL_NETWORKS = "0.0.0.0/0"
        val ALL_IPS = listOf(IPV4_ALL_NETWORKS, IPV6_ALL_NETWORKS)
        val IPV4_PUBLIC_NETWORKS =
            setOf(
                "0.0.0.0/5",
                "8.0.0.0/7",
                "11.0.0.0/8",
                "12.0.0.0/6",
                "16.0.0.0/4",
                "32.0.0.0/3",
                "64.0.0.0/2",
                "128.0.0.0/3",
                "160.0.0.0/5",
                "168.0.0.0/6",
                "172.0.0.0/12",
                "172.32.0.0/11",
                "172.64.0.0/10",
                "172.128.0.0/9",
                "173.0.0.0/8",
                "174.0.0.0/7",
                "176.0.0.0/4",
                "192.0.0.0/9",
                "192.128.0.0/11",
                "192.160.0.0/13",
                "192.169.0.0/16",
                "192.170.0.0/15",
                "192.172.0.0/14",
                "192.176.0.0/12",
                "192.192.0.0/10",
                "193.0.0.0/8",
                "194.0.0.0/7",
                "196.0.0.0/6",
                "200.0.0.0/5",
                "208.0.0.0/4",
            )
        val LAN_BYPASS_ALLOWED_IPS = setOf(IPV6_ALL_NETWORKS) + IPV4_PUBLIC_NETWORKS
    }
}
