const { BrowserWindow, Menu, dialog, screen } = require('electron')
const path = require('path');

const resolve = (file) => path.resolve(__dirname, file);

const addSource = (srcUrl) => {
    let finalUrl = srcUrl

    let connector = '?'
    if (finalUrl.indexOf('?') > -1) {
        connector = '&'
    }

    finalUrl += `${connector}from=PCsoft`

    return finalUrl
}

class WindowManager {
    constructor(app) {
        Menu.setApplicationMenu(null);
        this.app = app;
    }

    createModalWindow(parent) {
        const size = parent.getContentSize();
        const childModal = new BrowserWindow({
            parent: parent,
            width: size[0] - 100,
            height: size[1] - 100,
            modal: false,
            maximizable: false,
            minimizable: false,
            movable: true,
            show: false,
            icon: path.join(__dirname, '/resources/icon.png'),
            webPreferences: {
                contextIsolation: true,
                // preload: resolve('preload.js'),
            }
        });
        
        childModal.on('ready-to-show', async () => {
            childModal.webContents.insertCSS(`
                header, footer{
                    display: none !important;
                }
            `)
            
            // const url = childModal.webContents.getURL();
            // if(/135editor.com\/$/.test(url)) {
            //     childModal.close();
            //     await parent.webContents.executeJavaScript('window.loged_user = false;getUnreadMsgNum()', true);
            // } else {
            //     childModal.show();
            // }

            childModal.show();
            parent.webContents.send('HIDE_LOADIND');
        })
        childModal.webContents.on('new-window', (event, url) => {

             if (/(style|yangshi)_id=/.test(url)) {
                event.preventDefault();
                childModal.close();
                parent.webContents.executeJavaScript(`window.history.pushState(null, null, '${url}');autoUseStyle();`, true).then(()=>{})
                
            } else if(!/\/users\/login/.test(url)) {
                event.preventDefault();
                childModal.loadURL(addSource(url));
            }
        })
        childModal.webContents.on('dom-ready', (event) => {
            childModal.webContents.insertCSS(`
                header, footer{
                    display: none !important;
                }
                #left-logo:hover .menu-logo-hover,
                #left-logo:hover .menu-logo-img {
                    display: none !important;
                }
                #link-298 {
                    display: none !important;
                }
            `)
            childModal.webContents.executeJavaScript('window.onbeforeunload=null', true).then(()=>{})
        })
        return childModal;
    }

    createMainWindow() {
        let childModal;
        const mainWindow = new BrowserWindow({
            width: screen.getPrimaryDisplay().workAreaSize.width,
            height: screen.getPrimaryDisplay().workAreaSize.height,
            icon: path.join(__dirname, '/resources/icon.png'),
            webPreferences: {
                preload: resolve('preload.js'),
                contextIsolation: true,
                nodeIntegration: true
            }
        });


        mainWindow.webContents.on('new-window', (event, url) => {
            event.preventDefault();
            if(/changeteam/.test(url)) {
                mainWindow.webContents.reload();
                console.log(url);
                
                return;
            }

            // text-editor
            // renderer-editor

            mainWindow.webContents.send('SHOW_LOADBACKGROUND')
            childModal = this.createModalWindow(mainWindow)
            childModal.loadURL(addSource(url));
            childModal.on('close', async () => {
                if (/135editor.com/.test(url)) {
                    let logineState = await childModal.webContents.executeJavaScript('checkLogin()', true);
                    if (logineState) {
                        logineState = await mainWindow.webContents.executeJavaScript('checkLogin()', true);
                        // !logineState && await mainWindow.webContents.executeJavaScript('getUnreadMsgNum()', true);
                        !logineState && mainWindow.webContents.reload();
                    }
                }
            })
            childModal.on('closed', () => {
                setTimeout(() => {
                    mainWindow.webContents.send('HIDE_LOADBACKGROUND')
                }, 0)
            })
        })

        mainWindow.on('resize',(e) =>{
            mainWindow.webContents.executeJavaScript('setTimeout(function(){ console.log("xxxx");$(window).trigger("resize");},300);', true).then(()=>{});
            // console.log('resize');
        })

        if (!this.app.isPackaged) {
            //console.log('devmode');
            mainWindow.webContents.openDevTools();
        }

        mainWindow.webContents.on('dom-ready', (event) => {
            mainWindow.webContents.insertCSS(`
                .hztg-link{
                    display: none !important;
                }
                #left-advertises {
                    display: none !important;
                }
                .ifo a{
                    display: none !important;
                }
                .ifo > div.text-center {
                    display: none;
                }
                .ifo > div:first-child > p {
                    display: none !important;
                }
                #left-logo:hover .menu-logo-hover,
                #left-logo:hover .menu-logo-img {
                    display: none !important;
                }
                #image-list>div:nth-child(1) button {
                    display: none !important;
                }
                #image-list>div:nth-child(1) button~a {
                    flex: 1;
                    margin: 0 5px;
                }
                #link-298 {
                    display: none !important;
                }
            `);
            // mainWindow.webContents.executeJavaScript('var logout = document.querySelector(\'a[href="/users/logout"]\');if(logout){logout.setAttribute("target", "_blank")};var ateams = document.querySelectorAll("a.team");if(ateams.length){for(var i=0,ci;(ci=ateams[i]);i++){ci.setAttribute("target", "_blank");ci.setAttribute("href", "/changeteam")}}', true).then(()=>{})
            mainWindow.webContents.executeJavaScript('window.onbeforeunload=null', true).then(()=>{})
        })

        mainWindow.on('close', (e) => {
            if (!this.forceClose) {
                e.preventDefault();
                mainWindow.webContents.executeJavaScript('var html = current_editor.getContent();if(html)localStorage._135content = html;', true).then(()=>{});
                dialog.showMessageBox({
                    type: 'info',
                    title: '确定要关闭吗？',
                    message: '是否确认编辑的内容已保存或者复制使用，否则内容可能丢失',
                    defaultId: 0,
                    buttons: ['取消', '确定']
                }).then(result => {
                    // console.log(result);
                    if (result.response === 1) {
                        this.forceClose = true;
                        childModal = null;
                        mainWindow.close();
                    }
                }).catch(err => {
                    console.log(err)
                })
            } else {
                this.app.exit();
            }
        })

        mainWindow.on('closed', () => {
        })

        // const clearObj = {
        //     storages: ['appcache', 'filesystem', 'indexdb', 'localstorage', 'shadercache', 'websql', 'serviceworkers', 'cachestorage'],
        //   };
        // mainWindow.webContents.session.clearStorageData(clearObj)
        // mainWindow.webContents.session.clearCache();

        // mainWindow.maximize();
        mainWindow.loadURL(addSource('https://www.135editor.com/'));
        // mainWindow.setAlwaysOnTop(true, 'screen');

        // mainWindow.webContents.openDevTools();
        this.mainWindow = mainWindow;
        this.forceClose = false;
    }

    createMainWindowIfNeed() {
        if (BrowserWindow.getAllWindows().length === 0) {
            this.createMainWindow();
        }
    }
}

module.exports = {
    WindowManager
}