
import { autoUpdater} from "electron-updater"
import { dialog} from "electron";
import { getStoreValue } from "../store";

/**
 * updater.js
 *
 * Please use manual update only when it is really required, otherwise please use recommended non-intrusive auto update.
 *
 * Import steps:
 * 1. create `updater.js` for the code snippet
 * 2. require `updater.js` for menu implementation, and set `checkForUpdates` callback from `updater` for the click property of `Check Updates...` MenuItem.
 */

let updater
autoUpdater.autoDownload = false

autoUpdater.on('error', (error) => {
  dialog.showErrorBox('Error: ', error == null ? "unknown" : (error.stack || error).toString())
})

autoUpdater.on('update-available', () => {
  dialog.showMessageBox({
    type: 'info',
    title: '发现新版本',
    message: '发现新版本, 是否需要现在更新?',
    buttons: ['立即更新', '取消']
  }).then((buttonIndex) => {
    if (buttonIndex.response === 0) {
      autoUpdater.downloadUpdate()
    }
    else {
      updater.enabled = true
      updater = null
    }
  })
})

autoUpdater.on('update-not-available', () => {
  if (updater.toast){
    dialog.showMessageBox({
      type: 'info',
      title: '暂未发现新版本',
      message: '当前版本已经是最新的了'
    })
  }
  updater.enabled = true
  updater = null
})

autoUpdater.on('update-downloaded', () => {
  dialog.showMessageBox({
    type: 'info',
    title: '安装更新',
    message: '新版本已经下载结束, 应用即将退出并重新安装...'
  }).then(() => {
    setImmediate(() => autoUpdater.quitAndInstall())
  })
})

// export this to MenuItem click callback
export function  checkForUpdates (menuItem,toast=true) {
  if(menuItem!=null){
    updater = menuItem
    updater.enabled = false
    updater.toast = toast

    const h5_client_url=getStoreValue("h5_client_url")+"/update_files"

    autoUpdater.setFeedURL(h5_client_url)

    autoUpdater.checkForUpdates()
  }
}
