import { Injectable, inject } from '@angular/core';

import { resolveMobileAdapter } from '../logic/mobile-capacitor-adapter.rules';
import type { MobilePictureInPictureAdapter } from '../contracts/mobile.contracts';
import { WebMobilePictureInPictureAdapter } from '../adapters/web/web-mobile-picture-in-picture.adapter';
import { MobilePlatformService } from './mobile-platform.service';

/** Facade for stream pop-out while the app is backgrounded. */
@Injectable({ providedIn: 'root' })
export class MobilePictureInPictureService {
  private readonly mobilePlatform = inject(MobilePlatformService);
  private adapter: MobilePictureInPictureAdapter = new WebMobilePictureInPictureAdapter();
  private adapterReady: Promise<MobilePictureInPictureAdapter> | null = null;

  isSupported(): boolean {
    return this.adapter.isSupported();
  }

  enter(videoElement: HTMLVideoElement): Promise<void> {
    return this.ensureAdapter().then((adapter) => adapter.enter(videoElement));
  }

  exit(): Promise<void> {
    return this.ensureAdapter().then((adapter) => adapter.exit());
  }

  private ensureAdapter(): Promise<MobilePictureInPictureAdapter> {
    if (!this.adapterReady) {
      this.adapterReady = resolveMobileAdapter(
        this.mobilePlatform.runtime(),
        this.adapter,
        async () => {
          const { CapacitorMobilePictureInPictureAdapter } = await import('../adapters/capacitor/capacitor-mobile-picture-in-picture.adapter');

          return new CapacitorMobilePictureInPictureAdapter();
        }
      ).then((adapter) => {
        this.adapter = adapter;
        return adapter;
      });
    }

    return this.adapterReady;
  }
}
