/*
 * Copyright (C) 2026 SHX VPN
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 */

package org.strongswan.android.logic.autoconnect

import android.content.Context
import android.net.NetworkCapabilities
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build

/**
 * Reads the current Wi-Fi SSID.
 *
 * [WifiManager.connectionInfo] returns `"<unknown ssid>"` in the background on
 * Android 10+ unless the app is in the foreground or holds background location.
 * [NetworkCapabilities.transportInfo] is similarly redacted unless the
 * [android.net.ConnectivityManager.NetworkCallback] was registered with
 * `FLAG_INCLUDE_LOCATION_INFO` (API 31+).
 */
object SsidReader
{
	private const val UNKNOWN = "<unknown ssid>"

	fun from(context: Context, caps: NetworkCapabilities? = null): String?
	{
		fromWifiInfo(caps?.transportInfo as? WifiInfo)?.let { return it }
		@Suppress("DEPRECATION")
		val info = try
		{
			val wifi = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
			wifi?.connectionInfo
		}
		catch (_: Exception)
		{
			null
		}
		return fromWifiInfo(info)
	}

	fun fromWifiInfo(info: WifiInfo?): String?
	{
		if (info == null)
		{
			return null
		}
		normalize(info.ssid)?.let { return it }
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
		{
			normalize(info.passpointProviderFriendlyName)?.let { return it }
		}
		return null
	}

	fun normalize(raw: String?): String?
	{
		val ssid = raw?.removeSurrounding("\"")?.trim() ?: return null
		if (ssid.isEmpty() || ssid.equals(UNKNOWN, ignoreCase = true) || ssid == "0x")
		{
			return null
		}
		return ssid
	}
}
