// eslint-disable-next-line import/no-unresolved
import { NativeModules, NativeEventEmitter } from 'react-native';
import EventManager from '../../../../manager/eventManager';

const NativeExt = NativeModules.MiniAppFs;
const SuccMsg = "offlineFileReady succ";
const ListenEvent = "kOfflineFileReady";

let _emitter = null;
let _eventer = null;

const _initEmitter = function () {
  if (_emitter) return;
  _eventer = new EventManager();
  _emitter = new NativeEventEmitter(NativeExt);
  _emitter.addListener(ListenEvent, evt => _eventer.emit(evt.url, SuccMsg));
};

const waitEventEmit = function (eventName) {
  _initEmitter();
  return new Promise((resolve, reject) => {
    _eventer.once(eventName, res => resolve(res));
  });
};

export default {
  /**
   * 监听离线资源是否下载完成消息
   */
  async offlineFileReady(params) {
    if (!params || !params.url) {
      throw new Error("url is undefined");
    }

    const isReady = await NativeExt.checkOfflineFileReady(params);
    if (isReady) {
      return SuccMsg;
    }

    return await waitEventEmit(params.url);
  }
}
