const { ipcRenderer } = require('electron');

const windowMessager = document.getElementsByClassName('window')[0];
const tipMessager = document.getElementsByClassName('window')[1];
const modeInput = document.getElementsByName('clientMode');
const setCenter = () => {
    const left = window.innerWidth;
    const top = window.innerHeight;
    const offTop = top - windowMessager.offsetHeight;
    const offLeft = left - windowMessager.offsetWidth;
    windowMessager.style.top = offTop / 2 + 'px';
    windowMessager.style.left = offLeft / 2 + 'px';
};
const setTipMessageCenter = () => {
    const left = window.innerWidth;
    const top = window.innerHeight;
    const offTop2 = top - 206;
    const offLeft2 = left - 400;
    tipMessager.style.top = offTop2 / 2 + 'px';
    tipMessager.style.left = offLeft2 / 2 + 'px';
};
setCenter();
setTimeout(() => {
    windowMessager.style.opacity = 1;
});
const drag = new Drag();
drag.drag(windowMessager);
window.onresize = setCenter;

const changeHandle = () => {
    for (let item of modeInput) {
        item.onchange = function (e) {
            const libPath = document.getElementsByClassName('lib-path-content')[0];
            const prjPath = document.getElementsByClassName('prj-path-content')[0];
            const onlinePrjPath = document.getElementsByClassName('online-prj-path-content')[0];
            if (this.value === clientModeEnum.ONLINE) {
                libPath.style.display = 'none';
                prjPath.style.display = 'none';
                onlinePrjPath.style.display = 'flex';
            } else {
                libPath.style.display = 'flex';
                prjPath.style.display = 'flex';
                onlinePrjPath.style.display = 'none';
            }
        };
    }
};

changeHandle();
const libItemBindClick = (listName) => {
    const libList = windowMessager.getElementsByClassName(listName)[0];
    if (!libList) {
        return;
    }
    const list = libList.getElementsByTagName('li');
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        item.onclick = function (e) {
            e.stopPropagation();
            e.preventDefault();
            const doubleClick = this.getAttribute('class').includes('comm-list-item-active');
            const dot = (e.target.getAttribute('class') || '').includes('input-dot');
            if (doubleClick || dot) {
                ipcRenderer.send('client-setting', { cmd: listName.includes('lib') ? 'changeLibPath' : 'changeProjectPath' });
            } else {
                for (let item of list) {
                    item.classList.remove('comm-list-item-active');
                }
                this.classList.add('comm-list-item-active');
            }
            updateTagStatus(libList);
        };
        const span = item.getElementsByTagName('span')[0];
        span.onclick = function (e) {
            e.stopPropagation();
            e.preventDefault();
            for (let item of list) {
                item.removeAttribute('data-dot');
            }
            this.parentElement.setAttribute('data-dot', 'active');
            ipcRenderer.send('client-setting', { cmd: listName.includes('lib') ? 'libDot' : 'projectPathDot' });
        };
    }
};
libItemBindClick('libList');
libItemBindClick('projectPathList');
const messager = (data) => {
    tipMessager.innerHTML = warnTemplate(data);
    drag.drag(tipMessager);
    setTipMessageCenter();
    tipMessager.style.display = 'block';
    document.getElementsByClassName('window-mask')[0].style.display = 'block';
};
const closeMessager = () => {
    tipMessager.innerHTML = '';
    tipMessager.style.display = 'none';
    document.getElementsByClassName('window-mask')[0].style.display = 'none';
};
const islibPathEqual = (libPath1, libPath2) => {
    if (libPath1.length !== libPath2.length) {
        return false;
    }
    for (let i = 0; i < libPath1.length; i++) {
        if (libPath1[i] !== libPath2[i]) {
            return false;
        }
    }
    return true;
};
function isValidPath(data) {
    const reg = /[*?\/|\\]$/g;
    if (reg.test(data.projectPath)) {
        return { ret: false, path: data.projectPath };
    }
    if (reg.test(data.backupPath)) {
        return { ret: false, path: data.backupPath };
    }
    for (let item of data.libPath) {
        if (reg.test(item)) {
            return { ret: false, path: item };
        }
    }
    return { ret: true, path: '' };
}

const isCheckPath = () => {
    const libList = windowMessager.getElementsByClassName('libList')[0];
    const libs = libList.getElementsByTagName('input');
    const libPaths = Array.from(libs).map((item) => item.value);
    const projectPaths = windowMessager.getElementsByClassName('projectPathList')[0].getElementsByTagName('input');
    const projectPath = Array.from(projectPaths).map((item) => item.value);
    const backupPath = windowMessager.getElementsByClassName('backupPath')[0].value;
    const mode = Array.from(modeInput).filter((item) => {
        if (item.checked) {
            return item;
        }
    })[0].value;
    const { projectDir, libraryDir, appOnlineBackupDir, clientMode } = param;
    if (
        clientMode === mode &&
        islibPathEqual(projectDir, projectPath) &&
        appOnlineBackupDir === backupPath &&
        islibPathEqual(libraryDir, libPaths)
    ) {
        return { res: false, code: 0, data: {} };
    }
    if (!libPaths || libPaths.length === 0 || !projectPath || projectPath.length === 0 || !backupPath) {
        messager({ title: 'error', content: 'errorText', icon: 'error' });
        return { res: false, code: -1, data: {} };
    }
    const data = {
        libPath: libPaths,
        projectPath,
        backupPath,
        clientMode: mode,
    };
    const res = isValidPath(data);
    if (!res.ret) {
        messager({ title: 'error', content: 'invalidPath', icon: 'error', path: res.path });
        return { res: false, code: -1, data: {} };
    }
    return { res: true, code: 1, data };
};
const move = (step, list) => {
    let liIndex = 0;
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        const isActive = item.getAttribute('class').includes('comm-list-item-active');
        if (isActive) {
            liIndex = i;
        }
    }
    if (step > 0) {
        list[liIndex + step].parentNode.insertBefore(list[liIndex + step], list[liIndex]);
    } else {
        list[liIndex + step].parentNode.insertBefore(list[liIndex], list[liIndex + step]);
    }
};
const updateTagStatus = (libList) => {
    const parent = libList.parentNode;
    const list = libList.getElementsByTagName('li');
    const currentIndex = () => {
        for (let i = 0; i < list.length; i++) {
            const item = list[i];
            if (item.getAttribute('class').includes('comm-list-item-active')) {
                return i;
            }
        }
        return null;
    };
    del = parent.getElementsByClassName('icon_operate_delete')[0];
    up = parent.getElementsByClassName('icon_operate_up')[0];
    down = parent.getElementsByClassName('icon_operate_down')[0];
    if (list.length > 1) {
        if (currentIndex() === 0) {
            up && up.classList.add('disabled');
            up && up.classList.add('pointer-events-none');
            down && down.classList.remove('disabled');
            down && down.classList.remove('pointer-events-none');
            del.classList.remove('disabled');
            del.classList.remove('pointer-events-none');
        } else if (currentIndex() === list.length - 1) {
            up && up.classList.remove('disabled');
            up && up.classList.remove('pointer-events-none');
            down && down.classList.add('disabled');
            down && down.classList.add('pointer-events-none');
            del.classList.remove('disabled');
            del.classList.remove('pointer-events-none');
        } else if (currentIndex()) {
            up && up.classList.remove('disabled');
            up && up.classList.remove('pointer-events-none');
            down && down.classList.remove('disabled');
            down && down.classList.remove('pointer-events-none');
            del.classList.remove('disabled');
            del.classList.remove('pointer-events-none');
        }
    } else {
        del.classList.add('disabled');
        del.classList.add('pointer-events-none');
        up && up.classList.add('disabled');
        up && up.classList.add('pointer-events-none');
        down && down.classList.add('disabled');
        down && down.classList.add('pointer-events-none');
    }
};
function parseDom(nodelist) {
    var objE = document.createElement('div');
    objE.innerHTML = nodelist;
    return objE.childNodes[0];
}
let request;
document.addEventListener('click', (e) => {
    const libList = windowMessager.getElementsByClassName('libList')[0];
    const projectList = windowMessager.getElementsByClassName('projectPathList')[0];
    if (e.button === 0) {
        let cmd = e.target.getAttribute('cmd');
        switch (cmd) {
            case 'Confirm': {
                res = isCheckPath();
                ipcRenderer.send('client-setting', { cmd, data: request });
                windowMessager.style.opacity = 0;
                break;
            }
            case 'changeLaunchType': {
                const res = isCheckPath();
                if (res.code >= 0) {
                    messager({ title: 'LCEDA', content: 'switchMode', icon: 'question', confirm: true });
                    request = res.data;
                }
                break;
            }
            case 'libDelOne': {
                const list = libList.getElementsByTagName('li');
                if (list.length > 1) {
                    for (let item of list) {
                        const isActive = item.getAttribute('class').includes('comm-list-item-active');
                        if (isActive) {
                            libList.removeChild(item);
                            break;
                        }
                    }
                }
                updateTagStatus(libList);
                break;
            }
            case 'libAddOne': {
                const list = libList.getElementsByTagName('li');
                if (list.length >= 10) {
                    messager({ title: 'warn', content: 'warningText', icon: 'warning' });
                } else {
                    ipcRenderer.send('client-setting', { cmd });
                }
                break;
            }
            case 'projectPathDelOne': {
                const list = projectList.getElementsByTagName('li');
                if (list.length > 1) {
                    for (let item of list) {
                        const isActive = item.getAttribute('class').includes('comm-list-item-active');
                        if (isActive) {
                            projectList.removeChild(item);
                            break;
                        }
                    }
                }
                updateTagStatus(projectList);
                break;
            }
            case 'projectPathAddOne': {
                const list = projectList.getElementsByTagName('li');
                if (list.length >= 10) {
                    messager({ title: 'warn', content: 'warningText', icon: 'warning' });
                } else {
                    ipcRenderer.send('client-setting', { cmd });
                }
                break;
            }
            case 'projectPathMoveUp': {
                const list = projectList.getElementsByTagName('li');
                move(-1, list);
                updateTagStatus(projectList);
                break;
            }
            case 'projectPathMoveDown': {
                const list = projectList.getElementsByTagName('li');
                move(1, list);
                updateTagStatus(projectList);
                break;
            }
            case 'close':
                closeMessager();
                ipcRenderer.send('client-setting', { cmd });
                break;
            case 'Cancel':
                closeMessager();
                ipcRenderer.send('client-setting', { cmd });
                windowMessager.style.opacity = 0;
                break;
            case '_settings':
                ipcRenderer.send('client-setting', { cmd });
                break;
            default:
                break;
        }
    }
});
ipcRenderer.on('client-setting', (e, arg) => {
    const libList = windowMessager.getElementsByClassName('libList')[0];
    const projectList = windowMessager.getElementsByClassName('projectPathList')[0];
    switch (arg.cmd) {
        case 'libAddOne': {
            libList.appendChild(parseDom(setLibItemPath(arg.path)));
            libItemBindClick('libList');
            updateTagStatus(libList);
            break;
        }
        case 'projectPathAddOne': {
            projectList.appendChild(parseDom(setLibItemPath(arg.path)));
            libItemBindClick('projectPathList');
            updateTagStatus(projectList);
            break;
        }
        case 'changeLibPath': {
            const list = libList.getElementsByTagName('li');
            for (let item of list) {
                const isActive = item.getAttribute('class').includes('comm-list-item-active');
                if (isActive) {
                    item.getElementsByTagName('input')[0].value = arg.path;
                    break;
                }
            }
            break;
        }
        case 'changeProjectPath': {
            const list = projectList.getElementsByTagName('li');
            for (let item of list) {
                const isActive = item.getAttribute('class').includes('comm-list-item-active');
                if (isActive) {
                    item.getElementsByTagName('input')[0].value = arg.path;
                    break;
                }
            }
            break;
        }
        case 'libDot': {
            const list = libList.getElementsByTagName('li');
            for (let item of list) {
                const isActive = item.getAttribute('data-dot');
                if (isActive) {
                    item.getElementsByTagName('input')[0].value = arg.path;
                    break;
                }
            }
            break;
        }
        case 'projectPathDot': {
            const list = projectList.getElementsByTagName('li');
            for (let item of list) {
                const isActive = item.getAttribute('data-dot');
                if (isActive) {
                    item.getElementsByTagName('input')[0].value = arg.path;
                    break;
                }
            }
            break;
        }
        case 'backupPath': {
            const input = windowMessager.querySelector('input[data-attritem-input="backupPath"]');
            input.value = arg.path;
            break;
        }
    }
});
