import { CapacitorBarcodeScanner, CapacitorBarcodeScannerCameraDirection, CapacitorBarcodeScannerScanOrientation, CapacitorBarcodeScannerTypeHint } from "@capacitor/barcode-scanner";
import { modalController, toastController } from "@ionic/vue";
import QRCode from "@/components/qr-scanner/index.vue";

export interface QRScanResult {
  text: string;
  format: string;
}

export interface ScannerOptions {
  title?: string;
}

export function useQRScanner() {
  const { t } = useI18n();
  const { vibrate } = useHaptics();
  const platform = usePlatform();

  async function open(options?: ScannerOptions) {
    return new Promise<string>(async (resolve, reject) => {
      try {
        vibrate();
        if (platform === "browser") {
          const modal = await modalController.create({
            component: QRCode,
            componentProps: {
              onClose: () => modal.dismiss(),
              onError: (error) => {
                toastController.create({
                  message: String(error),
                  duration: 2000,
                  position: "bottom",
                  color: "danger",
                }).then(toast => toast.present());
              },
              onSuccess: (result: string) => {
                toastController.create({
                  message: String(result),
                  duration: 2000,
                  position: "bottom",
                  color: "success",
                }).then(toast => toast.present());
                modal.dismiss(result);
              },
            },
            animated: false,
          });
          await modal.present();
          modal.onDidDismiss<string>().then((res) => {
            if (res.data)
              resolve(res.data);

            reject();
          });
        }
        else {
          const result = await CapacitorBarcodeScanner.scanBarcode({
            hint: CapacitorBarcodeScannerTypeHint.QR_CODE,
            scanInstructions: options?.title || t("scanner.hint"),
            cameraDirection: CapacitorBarcodeScannerCameraDirection.BACK,
            scanOrientation: CapacitorBarcodeScannerScanOrientation.PORTRAIT,
          });

          vibrate();
          resolve(result.ScanResult);
        }
      }
      catch (error: any) {
        console.log("error.message", error.message);
        if (error.code !== "OS-PLUG-BARC-0006") {
          const toast = await toastController.create({
            message: t("scanner.openError"),
            duration: 2000,
            position: "bottom",
            color: "danger",
          });
          await toast.present();
          reject();
        }
      }
    });
  }
  function close() {
  }

  return {
    open,
    close,
  };
}
