import { Platform } from 'react-native';
import NativeSpallaCore from '../specs/NativeSpallaCore';
import { httpPostJson } from './http';
import type { StreamConfig } from './streamConfig';

// Thin wrapper over the precompiled spalla-core TurboModule: all the
// envelope/batching/pacing logic lives in the native binary. This module only
// bridges the transport (XHR survives Android PiP, so POSTs stay in JS).
NativeSpallaCore.setPostHandler((requestId, url, bodyJson) => {
  let body: unknown;
  try {
    body = JSON.parse(bodyJson);
  } catch {
    // Never let a malformed envelope take playback down with it.
    NativeSpallaCore.completePost(requestId, false);
    return;
  }
  httpPostJson(url, body)
    .then((response) => NativeSpallaCore.completePost(requestId, response.ok))
    .catch(() => NativeSpallaCore.completePost(requestId, false));
});

export function getLocalizador(): string {
  return NativeSpallaCore.getLocalizador();
}

export type TelemetrySessionOptions = {
  contentId: string;
  uid: string;
  getData?: () => Record<string, unknown>;
};

export class TelemetrySession {
  private handle: number | null;
  private readonly getData?: () => Record<string, unknown>;

  constructor(options: TelemetrySessionOptions) {
    this.getData = options.getData;
    this.handle = NativeSpallaCore.telemetryCreate(
      options.contentId,
      options.uid,
      Platform.OS,
      String(Platform.Version)
    );
  }

  setConfig(config: StreamConfig) {
    if (this.handle != null) {
      NativeSpallaCore.telemetrySetConfig(this.handle, JSON.stringify(config));
    }
  }

  setData(data: Record<string, unknown>) {
    if (this.handle != null) {
      NativeSpallaCore.telemetrySetData(this.handle, JSON.stringify(data));
    }
  }

  private syncData() {
    if (this.handle != null && this.getData) {
      this.setData(this.getData());
    }
  }

  setCdn(name: string) {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetrySetCdn(this.handle, name);
    }
  }

  event(tipo: string, extras?: Record<string, unknown>) {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryEvent(
        this.handle,
        tipo,
        extras ? JSON.stringify(extras) : ''
      );
    }
  }

  keyEvent(tipo: string, extras?: Record<string, unknown>) {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryKeyEvent(
        this.handle,
        tipo,
        extras ? JSON.stringify(extras) : ''
      );
    }
  }

  errorEvent(tipo: string, code: string, message: string) {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryErrorEvent(this.handle, tipo, code, message);
    }
  }

  onPlay() {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryOnPlay(this.handle);
    }
  }

  onPause() {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryOnPause(this.handle);
    }
  }

  onPlaying() {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryOnPlaying(this.handle);
    }
  }

  onSeek() {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryOnSeek(this.handle);
    }
  }

  onEnded() {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryOnEnded(this.handle);
    }
  }

  onTimeUpdate(time: number) {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryOnTimeUpdate(this.handle, time);
    }
  }

  // Emits viewend, flushes and releases the native session; in-flight POSTs
  // still complete against the native queue before it is collected.
  end() {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryEnd(this.handle);
      NativeSpallaCore.telemetryDestroy(this.handle);
      this.handle = null;
    }
  }

  flush() {
    if (this.handle != null) {
      this.syncData();
      NativeSpallaCore.telemetryFlush(this.handle);
    }
  }
}
