import { autoUpdater } from 'electron-updater'
import type { BrowserWindow } from 'electron'
import { ipcMain } from 'electron'
import log from './log'
import type ElectronStore from 'electron-store'
import type { SettingStore } from '/#/store'

autoUpdater.logger = log
log.info('App starting...')

type MessageType =
    | 'checking-for-update'
    | 'error'
    | 'update-available'
    | 'update-not-available'
    | 'download-progress'
    | 'update-downloaded'

export async function useUpdater(win: BrowserWindow, store: ElectronStore<SettingStore>) {
    function checkForUpdate() {
        autoUpdater.checkForUpdates()
    }

    function sendUpdateMessageToWindow(body: { type: MessageType; message: string }) {
        log.info(`[检查更新] ${body.type}: ${body.message}`)
        win.webContents.send('updater:message', body)
    }

    autoUpdater.on('checking-for-update', () => {
        sendUpdateMessageToWindow({ type: 'checking-for-update', message: '正在检查更新...' })
    })
    autoUpdater.on('update-available', (info) => {
        sendUpdateMessageToWindow({ type: 'update-available', message: `发现新版本 v${info.version}` })
    })
    autoUpdater.on('update-not-available', () => {
        sendUpdateMessageToWindow({ type: 'update-not-available', message: '当前已是最新版本~' })
    })
    autoUpdater.on('error', (err) => {
        sendUpdateMessageToWindow({ type: 'error', message: err.message })
    })
    autoUpdater.on('download-progress', (progress) => {
        sendUpdateMessageToWindow({
            type: 'download-progress',
            message: `正在下载新版本 ${Number(progress.percent).toFixed(2)}%`,
        })
    })
    autoUpdater.on('update-downloaded', () => {
        sendUpdateMessageToWindow({ type: 'update-downloaded', message: '下载完成' })

        setTimeout(() => {
            // 退出并安装更新包
            autoUpdater.quitAndInstall(false, true)
            win.destroy()
        }, 1500)
    })

    // 监听界面发送的检查更新事件
    ipcMain.on('updater:check', () => {
        checkForUpdate()
    })

    try {
        const feedURL = store.get('system.feedURL')
        if (feedURL) {
            // 设置更新地址
            autoUpdater.setFeedURL({
                provider: 'generic',
                url: feedURL as string,
            })

            // 检查更新
            checkForUpdate()
        }
    } catch (error: any) {
        sendUpdateMessageToWindow({ type: 'error', message: error.message })
    }
}
