package app.timesafari;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowInsetsController;
import android.view.WindowInsets;
import android.os.Build;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import com.getcapacitor.BridgeActivity;
import app.timesafari.safearea.SafeAreaPlugin;
import app.timesafari.sharedimage.SharedImagePlugin;
//import com.getcapacitor.community.sqlite.SQLite;

import android.content.SharedPreferences;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class MainActivity extends BridgeActivity {
    private static final String TAG = "MainActivity";
    private static final String SHARED_PREFS_NAME = "shared_image";
    private static final String KEY_BASE64 = "shared_image_base64";
    private static final String KEY_FILE_NAME = "shared_image_file_name";
    private static final String KEY_READY = "shared_image_ready";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Enable edge-to-edge display for modern Android
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ (API 30+)
            getWindow().setDecorFitsSystemWindows(false);
            
            // Set up system UI visibility for edge-to-edge
            WindowInsetsController controller = getWindow().getInsetsController();
            if (controller != null) {
                controller.setSystemBarsAppearance(
                    WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS | 
                    WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
                    WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS | 
                    WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
                );
                controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
            }
        } else {
            // Legacy Android (API 21-29)
            getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR |
                View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
            );
        }
        
        // Register SafeArea plugin
        registerPlugin(SafeAreaPlugin.class);
        
        // Register SharedImage plugin
        registerPlugin(SharedImagePlugin.class);
        
        // Register DailyNotification plugin
        registerPlugin(com.timesafari.dailynotification.DailyNotificationPlugin.class);
        
        // Initialize SQLite
        //registerPlugin(SQLite.class);
        
        // Handle share intent if app was launched from share sheet
        handleShareIntent(getIntent());
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleShareIntent(intent);
    }
    
    /**
     * Handle share intents (ACTION_SEND or ACTION_SEND_MULTIPLE)
     * Processes shared images and stores them in SharedPreferences for plugin to read
     */
    private void handleShareIntent(Intent intent) {
        if (intent == null) {
            return;
        }
        
        String action = intent.getAction();
        String type = intent.getType();
        
        boolean handled = false;
        
        // Handle single image share
        if (Intent.ACTION_SEND.equals(action) && type != null && type.startsWith("image/")) {
            Uri imageUri;
            // Use new API for API 33+ (Android 13+), fall back to deprecated API for older versions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri.class);
            } else {
                // Deprecated but still works on older versions
                @SuppressWarnings("deprecation")
                Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                imageUri = uri;
            }
            if (imageUri != null) {
                String fileName = intent.getStringExtra(Intent.EXTRA_TEXT);
                processSharedImage(imageUri, fileName);
                handled = true;
            }
        }
        // Handle multiple images share (we'll just process the first one)
        else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null && type.startsWith("image/")) {
            java.util.ArrayList<Uri> imageUris;
            // Use new API for API 33+ (Android 13+), fall back to deprecated API for older versions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri.class);
            } else {
                // Deprecated but still works on older versions
                @SuppressWarnings("deprecation")
                java.util.ArrayList<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                imageUris = uris;
            }
            if (imageUris != null && !imageUris.isEmpty()) {
                processSharedImage(imageUris.get(0), null);
                handled = true;
            }
        }
        
        // Clear the intent after handling to release URI permissions and prevent
        // network issues in WebView. This is critical for preventing the WebView
        // from losing network connectivity after processing shared content.
        if (handled) {
            intent.setAction(null);
            intent.setData(null);
            intent.removeExtra(Intent.EXTRA_STREAM);
            intent.setType(null);
            setIntent(new Intent());
            Log.d(TAG, "Cleared share intent after processing");
        }
    }
    
    /**
     * Process a shared image: read it, convert to base64, and write to temp file
     * Uses try-with-resources to ensure proper stream cleanup and prevent network issues
     */
    private void processSharedImage(Uri imageUri, String fileName) {
        // Extract filename from URI or use default (do this before opening streams)
        String actualFileName = fileName;
        if (actualFileName == null || actualFileName.isEmpty()) {
            String path = imageUri.getPath();
            if (path != null) {
                int lastSlash = path.lastIndexOf('/');
                if (lastSlash >= 0 && lastSlash < path.length() - 1) {
                    actualFileName = path.substring(lastSlash + 1);
                }
            }
            if (actualFileName == null || actualFileName.isEmpty()) {
                actualFileName = "shared-image.jpg";
            }
        }
        
        // Use try-with-resources to ensure streams are properly closed
        // This is critical to prevent resource leaks that can affect WebView networking
        try (InputStream inputStream = getContentResolver().openInputStream(imageUri);
             ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            
            if (inputStream == null) {
                Log.e(TAG, "Failed to open input stream for shared image");
                return;
            }
            
            // Read image bytes
            byte[] data = new byte[8192];
            int nRead;
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            byte[] imageBytes = buffer.toByteArray();
            
            // Convert to base64
            String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
            
            // Store in SharedPreferences for plugin to read
            storeSharedImageInPreferences(base64String, actualFileName);
            
            Log.d(TAG, "Successfully processed shared image: " + actualFileName);
        } catch (IOException e) {
            Log.e(TAG, "Error processing shared image", e);
        } catch (Exception e) {
            Log.e(TAG, "Unexpected error processing shared image", e);
        }
    }
    
    /**
     * Store shared image data in SharedPreferences for plugin to read
     * Plugin will read and clear the data when called
     */
    private void storeSharedImageInPreferences(String base64, String fileName) {
        try {
            SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(KEY_BASE64, base64);
            editor.putString(KEY_FILE_NAME, fileName);
            editor.putBoolean(KEY_READY, true);
            editor.apply();
            
            Log.d(TAG, "Stored shared image data in SharedPreferences");
        } catch (Exception e) {
            Log.e(TAG, "Error storing shared image in SharedPreferences", e);
        }
    }

} 