package de.datait.videokonverter

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager

/**
 * Setup-Bildschirm: Server-URL eingeben (wird beim ersten Start angezeigt).
 * Gespeicherte URL leitet direkt zur MainActivity weiter.
 */
class SetupActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // "reset" Extra: Setup erzwingen (von MainActivity gesendet)
        val forceSetup = intent.getBooleanExtra("force_setup", false)

        val prefs = PreferenceManager.getDefaultSharedPreferences(this)

        if (!forceSetup) {
            // Gespeicherte URL? Bereinigen + weiter zur MainActivity
            val savedUrl = prefs.getString("server_url", null)
            if (!savedUrl.isNullOrBlank()) {
                val cleanUrl = cleanServerUrl(savedUrl)
                if (cleanUrl != savedUrl) {
                    // Kaputte URL korrigieren (z.B. mit /tv/ Pfad)
                    prefs.edit().putString("server_url", cleanUrl).apply()
                }
                startMainActivity(cleanUrl)
                return
            }
        }

        setContentView(R.layout.activity_setup)

        val serverInput = findViewById<EditText>(R.id.serverUrl)
        val btnConnect = findViewById<Button>(R.id.btnConnect)
        val errorText = findViewById<TextView>(R.id.errorText)

        // Enter-Taste -> Verbinden
        serverInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                connectToServer(serverInput.text.toString(), errorText, prefs)
                true
            } else false
        }

        btnConnect.setOnClickListener {
            connectToServer(serverInput.text.toString(), errorText, prefs)
        }
    }

    private fun connectToServer(
        input: String,
        errorText: TextView,
        prefs: android.content.SharedPreferences
    ) {
        var url = input.trim()
        if (url.isBlank()) {
            errorText.text = "Bitte Server-Adresse eingeben"
            errorText.visibility = View.VISIBLE
            return
        }

        // Protokoll ergaenzen
        if (!url.contains("://")) {
            url = "http://$url"
        }

        // Port ergaenzen falls nicht vorhanden
        val hasPort = url.substringAfter("://").contains(":")
        if (!hasPort) {
            url = "$url:8080"
        }

        // Nur Schema + Host + Port behalten (Pfad entfernen)
        url = cleanServerUrl(url)

        // URL speichern
        prefs.edit().putString("server_url", url).apply()

        startMainActivity(url)
    }

    /** Nur Schema + Host + Port aus einer URL extrahieren */
    private fun cleanServerUrl(raw: String): String {
        return try {
            val uri = android.net.Uri.parse(raw)
            "${uri.scheme}://${uri.host}${if (uri.port > 0) ":${uri.port}" else ""}"
        } catch (e: Exception) {
            raw.trimEnd('/')
        }
    }

    private fun startMainActivity(serverUrl: String) {
        val intent = Intent(this, MainActivity::class.java)
        intent.putExtra("server_url", serverUrl)
        startActivity(intent)
        finish()
    }
}
