import { DeepLinkManager } from "../../utils/DeepLinkManager";
import { BootedDevice, IntentChooserResult, ObserveResult } from "../../models";
import { BaseVisualChange } from "./BaseVisualChange";
import { AdbClient } from "../../utils/android-cmdline-tools/AdbClient";
import { createGlobalPerformanceTracker } from "../../utils/PerformanceTracker";

export class HandleIntentChooser extends BaseVisualChange {
  private deepLinkManager: DeepLinkManager;

  /**
   * Create an TerminateApp instance
   * @param device - Optional device
   * @param adb - Optional AdbClient instance for testing
   */
  constructor(device: BootedDevice, adb: AdbClient | null = null) {
    super(device, adb);
    this.device = device;
    this.deepLinkManager = new DeepLinkManager(device);
  }

  /**
   * Execute intent chooser handling
   * @param preference - User preference for handling ("always", "just_once", or "custom")
   * @param customAppPackage - Optional specific app package to select for custom preference
   * @returns Promise with intent chooser handling results
   */
  async execute(
    preference: "always" | "just_once" | "custom" = "just_once",
    customAppPackage?: string
  ): Promise<IntentChooserResult> {
    const perf = createGlobalPerformanceTracker();
    perf.serial("handleIntentChooser");

    return this.observedInteraction(
      async (observeResult: ObserveResult) => {

        const viewHierarchy = observeResult.viewHierarchy;
        if (!viewHierarchy) {
          return { success: false, error: "View hierarchy not found" };
        }

        return await perf.track("handleChooser", () =>
          this.deepLinkManager.handleIntentChooser(
            viewHierarchy,
            preference,
            customAppPackage
          )
        );
      },
      {
        changeExpected: false,
        timeoutMs: 500,
        perf
      }
    );
  }
}
