/** @module native/Updater */
import { NativeModules, DeviceEventEmitter } from 'react-native';

const { Updater } = NativeModules;

/**
 * @typedef {Object} UpdateEvent 下载事件
 * @property {string} status 事件类型，downloading或downloaded
 * @property {number} progress 下载进度，0到100的整数
 * @property {number} current 已下载字节数
 * @property {number} all 总字节数
 */

/**
 * @callback UpdateCallback 下载回调
 * @param {UpdateEvent} event 下载事件
 */

/**
 * 下载更新包并自动安装, 下载过程中会发送Updater/downloading事件，下载完成时会发送Updater/downloaded事件
 * @param {string} url 更新地址
 * @param {UpdateCallback} cb 下载回调
 * @returns {Promise.<void>}
 */
export const update = async (url, cb) => {
  let handle1;
  let handle2;
  if (cb) {
    handle1 = DeviceEventEmitter.addListener('Updater/downloading', (event) => {
      cb({
        ...event,
        status: 'downloading',
      });
    });
    handle2 = DeviceEventEmitter.addListener('Updater/downloaded', (event) => {
      cb({
        ...event,
        status: 'downloaded',
      });
    });
  }
  await Updater.update(url);
  if (handle1) {
    handle1.remove();
  }
  if (handle2) {
    handle2.remove();
  }
};

/**
 * 取消当前更新进程
 * @returns {Promise.<void>}
 */
export const cancel = async () => {
  return Updater.cancel();
};
