package com.aethex.os;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceError;
import android.widget.Toast;
import android.app.AlertDialog;
import com.getcapacitor.BridgeActivity;

import android.util.Log;

public class MainActivity extends BridgeActivity {
    
    // Using onStart to hijack the process immediately after bridge init
    @Override
    public void onStart() {
        super.onStart();
        if (this.bridge != null && this.bridge.getWebView() != null) {
            loadCustomUrl();
        }
    }
    
    private void loadCustomUrl() {
        WebView webView = this.bridge.getWebView();
            
        // Set WebView background to BLACK
        webView.setBackgroundColor(0xFF000000);
        
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        
        // Add WebViewClient to catch errors
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                Log.e("AeThexOS", "WebView Error: " + error.getDescription());
                runOnUiThread(() -> {
                    new AlertDialog.Builder(MainActivity.this)
                        .setTitle("WebView Error")
                        .setMessage("Failed to load: " + request.getUrl() + "\n\nReason: " + error.getDescription())
                        .setPositiveButton("OK", null)
                        .show();
                });
            }
            
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i("AeThexOS", "Page Loaded: " + url);
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "Loaded: " + url, Toast.LENGTH_SHORT).show();
                });
            }
        });
        
        // Clear cache to ensure we aren't loading stale files
        webView.clearCache(true);
        webView.clearHistory();
        
        // Force load our local test file
        webView.loadUrl("file:///android_asset/public/test.html");
    }
}
