'use strict'

import { app, BrowserWindow, session, crashReporter } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require('path')

// 获取奔溃堆栈文件存放路径
let crashFilePath = ''
let crashDumpsDir = ''
try {
  // electron 低版本
  crashFilePath = path.join(app.getPath('temp'), app.getName() + ' Crashes')
  console.log('————————crash path:', crashFilePath)

  // electron 高版本
  crashDumpsDir = app.getPath('crashDumps')
  console.log('————————crashDumpsDir:', crashDumpsDir)
} catch (e) {
  console.error('获取奔溃文件路径失败', e)
}

// 开启crash捕获 官方建议写在app.on('ready')前
crashReporter.start({
  productName: 'jg-chemical-client',
  companyName: 'lnjgkj',
  submitURL: '', // 上传到服务器的地址
  uploadToServer: false, // 不上传服务器
  ignoreSystemCrashHandler: false, // 不忽略系统自带的奔溃处理，为 true 时表示忽略，奔溃时不会生成奔溃堆栈文件
})

app.on('gpu-process-crashed', (event, kill) => {
  console.warn('app:gpu-process-crashed', event, kill)
})

app.on('renderer-process-crashed', (event, webContents, kill) => {
  console.warn('app:renderer-process-crashed', event, webContents, kill)
})

app.on('render-process-gone', (event, webContents, details) => {
  console.warn('app:render-process-gone', event, webContents, details)
})

app.on('child-process-gone', (event, details) => {
  console.warn('app:child-process-gone', event, details)
})

app.disableHardwareAcceleration()

// 配置remote模块
const remote = require('@electron/remote/main')
remote.initialize()

const createWindow = async () => {
  const win = new BrowserWindow({
    frame: false,
    fullscreen: true,
    icon: 'src/assets/logo.ico',
    webPreferences: {
      webSecurity: false,
      // node集成，即是否注入node能力
      enableRemoteModule: true,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION, //上下文隔离
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION, //启用Node集成（是否完整的支持 node）
      // preload: path.join(__dirname, 'preload.js'),
      preload: path.join(app.getAppPath(), 'preload.js'),
      devTools: true,
    }
  })

  //监听窗口最大化、最小化事件 --- 主进程
  win.on('maximize', () => {
    win.webContents.send('mainWin-max', true)
  })
  win.on('unmaximize', () => {
    win.webContents.send('mainWin-max', false)
  })

  win.webContents.on('did-finish-load', function(event) {
    win.webContents.send('crash-file-path', `${crashFilePath} or ${crashDumpsDir}`)
  })

  // 配置remote模块
  remote.enable(win.webContents)

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    // win.webContents.openDevTools()
  } else {
    createProtocol('app')
    await win.loadURL('app://./index.html')
  }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their icon bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow().then(res => {
      console.log('app.on activate =>', res)
    })
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      // await installExtension(VUEJS_DEVTOOLS)
      // 新增的：安装vue-devtools
      await session.defaultSession.loadExtension(
        path.resolve(__dirname, 'D:\\jingang\\vue-devtools\\packages\\shell-chrome') //这个是刚刚build好的插件目录
      )
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  await createWindow()
  // 测试崩溃报告日志
  // process.crash()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
