//
//  EnableJIT.swift
//  MeloNX
//
//  Created by Stossy11 on 10/02/2025.
//

import Foundation
import UIKit

// MARK: - Server Address Management

/// Key for storing the JITEB server address in UserDefaults
private let JITEB_SERVER_ADDRESS_KEY = "jitServerAddress"

/// Returns the current JITEB server address.
/// Defaults to `[fd00::]` if no address is set.
func getJITServerAddress() -> String {
    return UserDefaults.standard.string(forKey: JITEB_SERVER_ADDRESS_KEY) ?? "[fd00::]"
}

/// Updates the JITEB server address in UserDefaults.
func setJITServerAddress(_ address: String) {
    UserDefaults.standard.set(address, forKey: JITEB_SERVER_ADDRESS_KEY)
}

// MARK: - JIT Enablement

/// Enables JIT execution by communicating with the JITEB server.
func enableJITEB() {
    guard let bundleID = Bundle.main.bundleIdentifier else {
        print("Error: Unable to retrieve bundle ID.")
        return
    }
    
    // Construct the URL using the current server address
    let serverAddress = getJITServerAddress()
    let urlString = "http://\(serverAddress):9172/launch_app/\(bundleID)"
    
    guard let address = URL(string: urlString) else {
        print("Error: Invalid server address.")
        return
    }
    
    // Send a network request to the JITEB server
    let task = URLSession.shared.dataTask(with: address) { data, response, error in
        if let error = error {
            print("Network error: \(error.localizedDescription)")
            return
        }
        
        guard let httpResponse = response as? HTTPURLResponse else {
            print("Error: Invalid server response.")
            return
        }
        
        guard let data = data else {
            print("Error: No data received from server.")
            return
        }
        
        // Show the launch status to the user
        DispatchQueue.main.async {
            if let rootViewController = UIApplication.shared.windows.last?.rootViewController {
                showLaunchAppAlert(jsonData: data, in: rootViewController)
            } else {
                print("Error: Unable to access root view controller.")
            }
        }
    }
    
    task.resume()
}

// MARK: - Launch App Response Handling

/// Struct to decode the JSON response from the JITEB server
struct LaunchApp: Codable {
    let ok: Bool
    let error: String?
    let launching: Bool
    let position: Int?
    let mounting: Bool
}

/// Displays an alert with the app launch status.
func showLaunchAppAlert(jsonData: Data, in viewController: UIViewController) {
    do {
        let result = try JSONDecoder().decode(LaunchApp.self, from: jsonData)
        
        var message = ""
        
        if let error = result.error {
            message = "Error: \(error)"
        } else if result.mounting {
            message = "App is mounting..."
        } else if result.launching {
            message = "App is launching..."
        } else {
            message = "App launch status unknown."
        }
        
        if let position = result.position {
            message += "\nPosition: \(position)"
        }
        
        let alert = UIAlertController(title: "Launch Status", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        
        DispatchQueue.main.async {
            viewController.present(alert, animated: true)
        }
        
    } catch {
        let alert = UIAlertController(title: "Decoding Error", message: error.localizedDescription, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        
        DispatchQueue.main.async {
            viewController.present(alert, animated: true)
        }
    }
}

// MARK: - Server Address Configuration

/// Displays an alert to allow the user to change the JITEB server address.
func configureJITServerAddress(in viewController: UIViewController) {
    let alert = UIAlertController(title: "Configure JITEB Server", message: "Enter the server address (e.g., [fd00::] or 192.168.1.100):", preferredStyle: .alert)
    
    alert.addTextField { textField in
        textField.placeholder = "Server Address"
        textField.text = getJITServerAddress()
    }
    
    alert.addAction(UIAlertAction(title: "Save", style: .default) { _ in
        if let textField = alert.textFields?.first, let newAddress = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) {
            setJITServerAddress(newAddress)
            print("JITEB server address updated to: \(newAddress)")
        }
    })
    
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
    
    viewController.present(alert, animated: true)
}