import fs from 'fs'
import { join } from 'path'
import initSqlJs from 'sql.js'
import { BrowserWindow, Menu, app, dialog, ipcMain, net, shell } from 'electron'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

let mainWindow
//菜单设置
const menu = Menu.buildFromTemplate([
    {
        label: app.name,
        submenu: [
            {
                label: '关于' + app.name,
                click: () => {
                    console.log('关于')
                },
            },
            { type: 'separator' },
            { label: '刷新', role: 'reload' },
            { label: '强制刷新', role: 'forceReload' },
            { type: 'separator' },
            { label: '退出' + app.name, role: 'quit' },
        ],
    },
    {
        label: '编辑',
        submenu: [
            { label: '撤销', role: 'undo' },
            { label: '重做', role: 'redo' },
            { type: 'separator' },
            { label: '剪切', role: 'cut' },
            { label: '复制', role: 'copy' },
            { label: '粘贴', role: 'paste' },
            { label: '删除', role: 'delete' },
            { type: 'separator' },
            { label: '全选', role: 'selectAll' },
        ],
    },
])
Menu.setApplicationMenu(menu)

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 900,
        height: 670,
        center: true,
        show: false,
        autoHideMenuBar: true,
        ...(process.platform === 'linux' ? { icon } : {}),
        webPreferences: {
            preload: join(__dirname, '../preload/index.js'),
            sandbox: false,
            webviewTag: true,
        },
    })

    mainWindow.on('ready-to-show', () => {
        mainWindow.show()
    })

    mainWindow.webContents.setWindowOpenHandler((details) => {
        shell.openExternal(details.url)
        return { action: 'deny' }
    })

    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
    }
}

app.whenReady().then(() => {
    electronApp.setAppUserModelId('com.local.archive.app')

    app.on('browser-window-created', (_, window) => {
        optimizer.watchWindowShortcuts(window)
    })

    // Open file
    app.on('open-file', (event, url) => {
        event.preventDefault()
        if (process.platform === 'darwin') {
            BrowserWindow.getFocusedWindow().webContents.send('open-file-vue', {
                data: url,
            })
        }
    })

    // IPC showOpenDialog
    ipcMain.handle('showOpenDialog', async (event, options) => {
        return new Promise((resolve) => {
            dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), options).then(result => {
                if (result.canceled) {
                    resolve({ code: 0 })
                } else {
                    resolve({ code: 200, paths: result.filePaths })
                }
            }).catch(err => {
                resolve({ code: 300, msg: err.message })
            })
        })
    })

    // IPC 操作数据库
    ipcMain.handle('dbSql', async (event, { path, sql, type = 'exec' }) => {
        // eslint-disable-next-line no-async-promise-executor
        return new Promise(async (resolve) => {
            try {
                const SQL = await initSqlJs()
                const db = new SQL.Database(fs.readFileSync(path))
                if (type === 'exec') {
                    resolve({ code: 200, data: db.exec(sql) })
                }
                if (type === 'run') {
                    resolve({ code: 200, data: db.run(sql) })
                }
            } catch (e) {
                resolve({ code: 300, data: e.message })
            }
        })
    })

    // IPC require
    ipcMain.handle('require', async (event, options) => {
        // eslint-disable-next-line no-async-promise-executor
        return new Promise(async (resolve) => {
            try {
                const request = net.request({ url: options.url })
                request.on('response', (response) => {
                    const code = response.statusCode
                    response.on('data', (chunk) => {
                        const data = chunk.toString()
                        if (code !== 200) {
                            return resolve({ code: 300, data: '错误' })
                        }
                        const res = data ? JSON.parse(data) : { code: 300, msg: '无数据' }
                        if (res.code === 200) {
                            resolve({ code: 200, data: res.data })
                        } else {
                            resolve({ code: 300, data: res.msg })
                        }
                    })
                })
                request.end()
            } catch (e) {
                resolve({ code: 300, data: e.message })
            }
        })
    })

    // IPC openDevTools
    ipcMain.handle('openDevTools', () => {
        BrowserWindow.getFocusedWindow().webContents.openDevTools()
    })

    // IPC openExternal
    ipcMain.handle('openExternal', async (event, options) => {
        if (options.url) {
            await shell.openExternal(options.url)
        }
    })

    //禁止多开 点击打开原来应用
    if (!app.requestSingleInstanceLock()) {
        app.quit()
    } else {
        createWindow()
        // 有人试图运行第二个实例，我们应该关注我们的窗口
        app.on('second-instance', (event, argv) => {
            if (process.platform !== 'darwin') {
                const url = argv[argv.length - 1]
                if (!mainWindow) {
                    createWindow()
                    return
                }
                if (mainWindow?.isMinimized()) {
                    mainWindow?.restore()
                }
                if (mainWindow?.isVisible()) {
                    mainWindow?.show()
                }
                mainWindow.focus()
                mainWindow.webContents.send('open-file-vue', { data: url })
            }
        })
    }

    app.on('activate', function () {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})


app.on('will-quit', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
