import {NativeModules} from 'react-native';

export type AudioPlayerReplaceAdditionalOptions = {
  position?: number;
  play?: boolean;
};

export type AudioPlayerReplaceOptions = {
  uri: string;
} & AudioPlayerReplaceAdditionalOptions;

export type AudioPlayerState = {
  isPlaying: boolean;
  isPaused: boolean;
  duration: number;
  playbackRate: number;
  position: number;
};

export interface AudioPlayerInterface {
  play(): Promise<void>;
  pause(): Promise<void>;
  replace(
    options: AudioPlayerReplaceOptions,
  ): Promise<{uri: string; duration: number}>;
  seekTo(position: number): void;
  setPlaybackRate(rate: number): void;
  getState(): AudioPlayerState;
  reset(): void;
}

export class AudioPlayer implements AudioPlayerInterface {
  private player: AudioPlayerInterface =
    NativeModules.RNAudioPlayer as AudioPlayerInterface;

  play() {
    return this.player.play();
  }

  pause() {
    return this.player.pause();
  }

  replace(options: AudioPlayerReplaceOptions) {
    return this.player.replace(options);
  }

  seekTo(position: number) {
    this.player.seekTo(position);
  }

  setPlaybackRate(rate: number) {
    this.player.setPlaybackRate(rate);
  }

  getState(): AudioPlayerState {
    return this.player.getState();
  }

  reset() {
    this.player.reset();
  }
}

export const audioPlayer = new AudioPlayer();
