/**
 * EXAMPLE: Integrating the Adblock Module into Your Browser
 *
 * This file demonstrates how to use the adblock module in your main
 * browser code. This is NOT meant to be compiled directly - copy the
 * relevant parts into your actual browser implementation.
 */

#include "extensions/adblock/adblock.h"
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>

/* Global adblock manager instance */
static AdblockManager *global_adblock_manager = NULL;

/**
 * Callback invoked when filter compilation completes
 */
static void on_filter_loaded(AdblockManager *manager, gboolean success,
                             GError *error, gpointer user_data) {
  if (success) {
    g_print("✓ Adblock filter loaded successfully!\n");
    g_print("  Total filters loaded: %u\n",
            adblock_manager_get_filter_count(manager));
  } else {
    g_warning("✗ Failed to load adblock filter: %s\n",
              error ? error->message : "Unknown error");
  }
}

/**
 * Initialize the adblock system
 * Call this early in your application startup (e.g., in main() or app activate)
 */
void browser_init_adblock(void) {
  /* Create the adblock manager with default store path */
  global_adblock_manager = adblock_manager_new(NULL);

  if (global_adblock_manager == NULL) {
    g_warning("Failed to create adblock manager");
    return;
  }

  /* Load the EasyList filter */
  GError *error = NULL;
  const gchar *filter_path = "src/extensions/adblock/easylist.txt";

  gboolean started = adblock_manager_load_from_file(
      global_adblock_manager, filter_path, "easylist", on_filter_loaded, NULL,
      &error);

  if (!started) {
    g_warning("Failed to start loading adblock filter: %s",
              error ? error->message : "Unknown error");
    if (error != NULL) {
      g_error_free(error);
    }
  }

  /* You can load additional filter lists here */
  /* Example:
  adblock_manager_load_from_file(
      global_adblock_manager,
      "src/extensions/adblock/easyprivacy.txt",
      "easyprivacy",
      on_filter_loaded,
      NULL,
      &error);
  */
}

/**
 * Apply adblock filters to a new WebView
 * Call this whenever you create a new WebKitWebView (e.g., new tab/window)
 */
void browser_apply_adblock_to_webview(WebKitWebView *web_view) {
  if (global_adblock_manager == NULL) {
    g_warning("Adblock manager not initialized");
    return;
  }

  if (!adblock_manager_is_enabled(global_adblock_manager)) {
    g_print("Adblock is disabled, not applying filters\n");
    return;
  }

  GError *error = NULL;
  gboolean success = adblock_manager_apply_to_web_view(global_adblock_manager,
                                                       web_view, &error);

  if (!success) {
    g_warning("Failed to apply adblock filters to WebView: %s",
              error ? error->message : "Unknown error");
    if (error != NULL) {
      g_error_free(error);
    }
  }
}

/**
 * Toggle adblock on/off
 * Call this from your settings UI or preferences
 */
void browser_toggle_adblock(gboolean enabled) {
  if (global_adblock_manager == NULL) {
    return;
  }

  adblock_manager_set_enabled(global_adblock_manager, enabled);
}

/**
 * Check if adblock is enabled
 */
gboolean browser_is_adblock_enabled(void) {
  if (global_adblock_manager == NULL) {
    return FALSE;
  }

  return adblock_manager_is_enabled(global_adblock_manager);
}

/**
 * Cleanup adblock on application shutdown
 */
void browser_cleanup_adblock(void) {
  if (global_adblock_manager != NULL) {
    adblock_manager_free(global_adblock_manager);
    global_adblock_manager = NULL;
  }
}

/* ========================================================================
 * EXAMPLE INTEGRATION INTO YOUR MAIN BROWSER CODE
 * ======================================================================== */

/**
 * Example 1: Application startup (in your main() function or activate callback)
 */
static void on_app_activate(GtkApplication *app, gpointer user_data) {
  /* Initialize adblock early */
  browser_init_adblock();

  /* ... rest of your application initialization ... */
  GtkWidget *window = gtk_application_window_new(app);

  /* ... create your UI ... */
}

/**
 * Example 2: Creating a new WebView/Tab
 */
WebKitWebView *create_new_tab(void) {
  /* Create WebKit settings */
  WebKitSettings *settings = webkit_settings_new();
  webkit_settings_set_enable_javascript(settings, TRUE);
  webkit_settings_set_enable_media_stream(settings, TRUE);

  /* Create user content manager */
  WebKitUserContentManager *content_manager = webkit_user_content_manager_new();

  /* Create WebView */
  WebKitWebView *web_view =
      WEBKIT_WEB_VIEW(webkit_web_view_new_with_settings(settings));

  /* IMPORTANT: Apply adblock filters to this WebView */
  browser_apply_adblock_to_webview(web_view);

  /* ... rest of your tab initialization ... */

  return web_view;
}

/**
 * Example 3: Adding a settings toggle in your UI
 */
static void on_adblock_toggle_changed(GtkSwitch *toggle, gboolean state,
                                      gpointer user_data) {
  browser_toggle_adblock(gtk_switch_get_active(toggle));

  g_print("Adblock %s\n", state ? "enabled" : "disabled");

  /* Note: You may want to reload existing tabs to apply the change */
}

void create_settings_ui(GtkWidget *settings_container) {
  GtkWidget *adblock_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);

  GtkWidget *label = gtk_label_new("Enable Ad Blocking:");
  GtkWidget *toggle = gtk_switch_new();

  gtk_switch_set_active(GTK_SWITCH(toggle), browser_is_adblock_enabled());

  g_signal_connect(toggle, "state-set", G_CALLBACK(on_adblock_toggle_changed),
                   NULL);

  gtk_box_pack_start(GTK_BOX(adblock_box), label, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(adblock_box), toggle, FALSE, FALSE, 0);
  gtk_container_add(GTK_CONTAINER(settings_container), adblock_box);
}

/**
 * Example 4: Application cleanup (in your shutdown handler)
 */
static void on_app_shutdown(GtkApplication *app, gpointer user_data) {
  /* Cleanup adblock */
  browser_cleanup_adblock();

  /* ... rest of your cleanup ... */
}

/**
 * Example 5: Complete main() function integration
 */
int main(int argc, char *argv[]) {
  GtkApplication *app =
      gtk_application_new("com.example.leafweb", G_APPLICATION_FLAGS_NONE);

  g_signal_connect(app, "activate", G_CALLBACK(on_app_activate), NULL);
  g_signal_connect(app, "shutdown", G_CALLBACK(on_app_shutdown), NULL);

  int status = g_application_run(G_APPLICATION(app), argc, argv);

  g_object_unref(app);

  return status;
}

/* ========================================================================
 * IMPORTANT NOTES FOR PRODUCTION USE
 * ======================================================================== */

/*
 * 1. FILTER LIST MANAGEMENT:
 *    - Download EasyList from: https://easylist.to/easylist/easylist.txt
 *    - Save it to: src/extensions/adblock/easylist.txt
 *    - Consider adding a filter update mechanism to fetch new versions
 *
 * 2. PERFORMANCE CONSIDERATIONS:
 *    - Filter compilation happens asynchronously
 *    - The compiled filters are cached by WebKit
 *    - You only need to compile filters once (unless they change)
 *
 * 3. MULTIPLE FILTER LISTS:
 *    - You can load multiple filter lists (EasyList, EasyPrivacy, etc.)
 *    - Each filter needs a unique identifier
 *    - All loaded filters will be applied to WebViews
 *
 * 4. WEBVIEW LIFECYCLE:
 *    - Apply filters to each WebView immediately after creation
 *    - The filters persist for the lifetime of that WebView
 *    - You don't need to reapply unless you change filter settings
 *
 * 5. ERROR HANDLING:
 *    - Always check return values and handle errors
 *    - Filter compilation can fail if the JSON is invalid
 *    - File I/O errors can occur if the filter list is missing
 *
 * 6. DEPENDENCIES:
 *    - Requires WebKit2GTK 2.24 or later
 *    - Requires json-glib for JSON parsing
 *    - Add to your build system: pkg-config --cflags --libs webkit2gtk-4.0
 * json-glib-1.0
 *
 * 7. BUILD INTEGRATION:
 *    Add to your meson.build or Makefile:
 *
 *    dependencies: [
 *      dependency('webkit2gtk-4.0'),
 *      dependency('json-glib-1.0'),
 *      dependency('gtk+-3.0')
 *    ]
 *
 * 8. TESTING:
 *    - Test with known ad-serving websites
 *    - Verify that ads are blocked in the Web Inspector (Network tab)
 *    - Check console output for filter loading messages
 */
