import { DeviceEventEmitter } from 'react-native';
import type { EmitterSubscription } from 'react-native';
import NativeVoice from './specs/v1/NativeVoice';
import type {
  SpeechEvents,
  SpeechRecognizedEvent,
  SpeechErrorEvent,
  SpeechResultsEvent,
  SpeechStartEvent,
  SpeechEndEvent,
  SpeechVolumeChangeEvent,
} from './VoiceModuleTypes';

type SpeechEvent = keyof SpeechEvents;

const EVENT_NAMES: SpeechEvent[] = [
  'onSpeechStart',
  'onSpeechRecognized',
  'onSpeechEnd',
  'onSpeechError',
  'onSpeechResults',
  'onSpeechPartialResults',
  'onSpeechVolumeChanged',
];

const NATIVE_MODULE_UNAVAILABLE_ERROR =
  'Voice native module is not available on HarmonyOS';

class RCTVoice {
  _loaded: boolean;
  _listeners: EmitterSubscription[] | null;
  _events: Required<SpeechEvents>;

  constructor() {
    this._loaded = false;
    this._listeners = null;
    this._events = {
      onSpeechStart: () => {},
      onSpeechRecognized: () => {},
      onSpeechEnd: () => {},
      onSpeechError: () => {},
      onSpeechResults: () => {},
      onSpeechPartialResults: () => {},
      onSpeechVolumeChanged: () => {},
    };
  }

  removeAllListeners() {
    if (this._listeners) {
      this._listeners.forEach(listener => listener.remove());
      this._listeners = null;
    }
  }

  destroy() {
    if (!this._loaded && !this._listeners) {
      return Promise.resolve();
    }
    if (!NativeVoice) {
      return Promise.reject(new Error(NATIVE_MODULE_UNAVAILABLE_ERROR));
    }
    return NativeVoice.destroySpeech().then(() => {
      this._loaded = false;
      this.removeAllListeners();
    });
  }

  start(locale: string, options: Object = {}) {
    if (!this._listeners) {
      this._listeners = EVENT_NAMES.map(key =>
        DeviceEventEmitter.addListener(key, (e: any) =>
          this._events[key](e),
        ),
      );
    }

    if (!NativeVoice) {
      return Promise.reject(new Error(NATIVE_MODULE_UNAVAILABLE_ERROR));
    }
    this._loaded = true;
    return NativeVoice.startSpeech(locale ?? '', options ?? {});
  }
  stop() {
    if (!this._loaded && !this._listeners) {
      return Promise.resolve();
    }
    if (!NativeVoice) {
      return Promise.reject(new Error(NATIVE_MODULE_UNAVAILABLE_ERROR));
    }
    return NativeVoice.stopSpeech();
  }
  cancel() {
    if (!this._loaded && !this._listeners) {
      return Promise.resolve();
    }
    if (!NativeVoice) {
      return Promise.reject(new Error(NATIVE_MODULE_UNAVAILABLE_ERROR));
    }
    return NativeVoice.cancelSpeech();
  }
  isAvailable(): Promise<0 | 1> {
    if (!NativeVoice) {
      return Promise.resolve(0);
    }
    return NativeVoice.isSpeechAvailable().then(
      (isAvailable): 0 | 1 => (isAvailable ? 1 : 0),
    );
  }

  /**
   * (Android-only 语义) HarmonyOS 无系统级语音识别引擎枚举能力,对齐 iOS 分支恒返回 undefined
   * */
  getSpeechRecognitionServices(): undefined {
    return undefined;
  }

  isRecognizing(): Promise<0 | 1> {
    if (!NativeVoice) {
      return Promise.resolve(0);
    }
    return NativeVoice.isRecognizing().then(
      (isRecognizing): 0 | 1 => (isRecognizing ? 1 : 0),
    );
  }

  set onSpeechStart(fn: (e: SpeechStartEvent) => void) {
    this._events.onSpeechStart = fn;
  }

  set onSpeechRecognized(fn: (e: SpeechRecognizedEvent) => void) {
    this._events.onSpeechRecognized = fn;
  }
  set onSpeechEnd(fn: (e: SpeechEndEvent) => void) {
    this._events.onSpeechEnd = fn;
  }
  set onSpeechError(fn: (e: SpeechErrorEvent) => void) {
    this._events.onSpeechError = fn;
  }
  set onSpeechResults(fn: (e: SpeechResultsEvent) => void) {
    this._events.onSpeechResults = fn;
  }
  set onSpeechPartialResults(fn: (e: SpeechResultsEvent) => void) {
    this._events.onSpeechPartialResults = fn;
  }
  set onSpeechVolumeChanged(fn: (e: SpeechVolumeChangeEvent) => void) {
    this._events.onSpeechVolumeChanged = fn;
  }
}

export type {
  SpeechEndEvent,
  SpeechErrorEvent,
  SpeechEvents,
  SpeechStartEvent,
  SpeechRecognizedEvent,
  SpeechResultsEvent,
  SpeechVolumeChangeEvent,
};
export default new RCTVoice();