import { type as osType } from '@tauri-apps/plugin-os';
import { getBundleType } from '@tauri-apps/api/app';
import { type Update, check } from '@tauri-apps/plugin-updater';
import { ElMessage as Toast } from 'element-plus';
import { $mitt, APP_UPDATE } from '../mitt-event';

/**
 * 检测更新
 */
export async function checkUpdate(showToast: boolean) {
  try {
    const res = await checkForUpdates();
    if (res) {
      $mitt.emit(APP_UPDATE, res);
    } else {
      showToast && Toast.success('当前已经是最新版本');
    }
  } catch (error: any) {
    showToast && Toast.error('检查更新失败');
  }
}

/**
 * 检测更新
 */
export async function checkForUpdates() {
  try {
    // 获取操作系统类型
    const platform = osType();
    const bundleType = await getBundleType();
    let target: string | undefined = undefined;
    if (platform === 'macos') {
      target = platform;
    } else if (platform === 'windows') {
      target = `${platform}`;
    } else if (platform === 'linux') {
      target = `${platform}/${bundleType}`;
    }
    // 根据操作系统类型确定更新配置
    const update: Update | null = await check({
      target,
    });
    return update;
  } catch (error: any) {
    console.log('error====', error);
    return Promise.reject('检测更新失败');
  }
}
