const { contextBridge } = require('electron')

class ContentBridge {
    constructor() {
        this.electron = require('electron');
        this.electron.ipcRenderer.on('SHOW_LOADBACKGROUND', (event, message) => {
            this.showBackgroundLayer()
        })
        this.electron.ipcRenderer.on('HIDE_LOADIND', (event, message) => {
            this.hideLoading()
        })
        this.electron.ipcRenderer.on('HIDE_LOADBACKGROUND', (event, message) => {
            this.hideBackgroundLayer()
        })
    }

    showBackgroundLayer() {
        if (this.background && this.background.parentNode) {
            return;
        }

        const width = document.documentElement.clientWidth;
        const height = document.documentElement.clientHeight;
        const zIndex = 9000050;

        const background = document.createElement('div');
        Object.assign(background.style, {
            width: width + "px",
            height: height + "px",
            position: "fixed",
            top: "0px",
            left: "0px",
            zIndex: zIndex,
            backgroundColor: "#000",
            opacity: ".7",
            transition: 'opacity 0.2s ease 0s',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
        })


        const loading = document.createElement('div');
        const img = document.createElement('img');
        img.src = '/img/loading.gif';
        loading.appendChild(img);

        background.appendChild(loading);
        this.background = background;
        this.loading = loading;

        document.body.appendChild(background);
    }

    hideLoading() {
        if(this.loading) {
            this.loading.remove();
            this.loading = null;
        }
    }

    hideBackgroundLayer() {
        if (this.background) {
            this.background.style.opacity = '0';
            setTimeout(()=>{
                this.background.remove();
                this.background = null;
            }, 200);
            
        }
    }

    getWindowSize() {
        const width = document.documentElement.clientWidth;
        const height = document.documentElement.clientHeight;
        return Promise.resolve({
            width,
            height
        })
    }
}
const brigde = new ContentBridge();
contextBridge.exposeInMainWorld('__content_bridge', {
});