from microdot import Microdot, send_file
from settings import Settings
import util.wifi as wifi
import json

controller = Microdot()
settings = Settings()

@controller.get('')
async def get_settings(request):
    """Get all settings."""
    return json.dumps(dict(settings)), 200, {'Content-Type': 'application/json'}

@controller.get('/wifi/station')
async def get_station_status(request):
    """Get WiFi station connection status."""
    status = wifi.get_sta_status()
    if status:
        return json.dumps(status), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Failed to get station status"}), 500

@controller.post('/wifi/station')
async def connect_station(request):
    """Connect to WiFi station with credentials."""
    try:
        data = request.json
        ssid = data.get('ssid')
        password = data.get('password', '')
        ip = data.get('ip')
        gateway = data.get('gateway')
        
        if not ssid:
            return json.dumps({"error": "SSID is required"}), 400
        
        # Save credentials to settings
        settings['wifi_station_ssid'] = ssid
        settings['wifi_station_password'] = password
        if ip:
            settings['wifi_station_ip'] = ip
        if gateway:
            settings['wifi_station_gateway'] = gateway
        settings.save()
        
        # Attempt connection
        result = wifi.connect(ssid, password, ip, gateway)
        if result:
            return json.dumps({
                "message": "Connected successfully",
                "ip": result[0],
                "netmask": result[1],
                "gateway": result[2],
                "dns": result[3] if len(result) > 3 else None
            }), 200, {'Content-Type': 'application/json'}
        else:
            return json.dumps({"error": "Failed to connect"}), 400
    except Exception as e:
        return json.dumps({"error": str(e)}), 500

@controller.get('/wifi/ap')
async def get_ap_config(request):
    """Get Access Point configuration."""
    config = wifi.get_ap_config()
    if config:
        # Also get saved settings
        config['saved_ssid'] = settings.get('wifi_ap_ssid')
        config['saved_password'] = settings.get('wifi_ap_password')
        config['saved_channel'] = settings.get('wifi_ap_channel')
        return json.dumps(config), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Failed to get AP config"}), 500

@controller.post('/wifi/ap')
async def configure_ap(request):
    """Configure Access Point."""
    try:
        data = request.json
        ssid = data.get('ssid')
        password = data.get('password', '')
        channel = data.get('channel')
        
        if not ssid:
            return json.dumps({"error": "SSID is required"}), 400
        
        # Validate channel (1-11 for 2.4GHz)
        if channel is not None:
            channel = int(channel)
            if channel < 1 or channel > 11:
                return json.dumps({"error": "Channel must be between 1 and 11"}), 400
        
        # Save to settings
        settings['wifi_ap_ssid'] = ssid
        settings['wifi_ap_password'] = password
        if channel is not None:
            settings['wifi_ap_channel'] = channel
        settings.save()
        
        # Configure AP
        wifi.ap(ssid, password, channel)
        
        return json.dumps({
            "message": "AP configured successfully",
            "ssid": ssid,
            "channel": channel
        }), 200, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 500

@controller.get('/wifi/station/credentials')
async def get_station_credentials(request):
    """Get saved WiFi station credentials (without password)."""
    return json.dumps({
        "ssid": settings.get('wifi_station_ssid', ''),
        "ip": settings.get('wifi_station_ip', ''),
        "gateway": settings.get('wifi_station_gateway', '')
    }), 200, {'Content-Type': 'application/json'}

@controller.put('/settings')
async def update_settings(request):
    """Update general settings."""
    try:
        data = request.json
        for key, value in data.items():
            settings[key] = value
        settings.save()
        return json.dumps({"message": "Settings updated successfully"}), 200, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 500

@controller.get('/page')
async def settings_page(request):
    """Serve the settings page."""
    return send_file('templates/settings.html')

