import { Intent } from '@blueprintjs/core';
import { Cache, Layers, Object3D } from 'three';
import { HostApplicationServices } from './ApplicationServices/HostApplicationServices';
import { ErrorMonitoring, ReportError } from './Common/ErrorMonitoring';
import { LogEnable, ReportErrorWrap } from './Common/Log';
import { copyTextToClipboard } from './Common/Utils';
import { userConfig } from './Editor/UserConfig';
import { LoadDefaultExr, LoadMetalEnv } from './Loader/EnvLoader';
import { AppToaster } from './UI/Components/Toaster';
import './UI/Css/blue.less';
import './UI/Css/golden.less';
import './UI/Css/style.less';
import './UI/Css/switchTheme.less';
import { WebCAD } from './UI/Layout/ApplicationLayout';

Cache.enabled = true;

//禁止用户选中
document.addEventListener("selectionchange", () =>
{
    let s = document.getSelection();
    if (s.anchorNode !== s.focusNode)
        s.empty();
    else if (s.rangeCount > 0)
    {
        let range = s.getRangeAt(0);
        if (range.startContainer.nodeName === "#text"
            && s.focusNode.parentElement.contentEditable !== "true"
            && s.focusNode.parentElement.parentElement.contentEditable !== "true") //#IZM3T
            s.empty();
    }
});

document.body.className = " light-golden";
//禁止右键
document.oncontextmenu = () => false;
//取消浏览器默认拖拽行为
document.ondragleave = e => e.preventDefault();
document.ondragenter = e => e.preventDefault();
document.ondragover = e => e.preventDefault();
//屏蔽浏览器页面缩放
document.addEventListener('wheel', (e: WheelEvent) =>
{
    if (e.ctrlKey)
    {
        e.returnValue = false;
        e.preventDefault();
        e.stopPropagation();
    }
}, { passive: false });

document.addEventListener("keydown", (e: KeyboardEvent) =>
{
    if (e.ctrlKey)
    {
        if (e.key === "-" || e.key === "=")
        {
            e.returnValue = false;
            e.preventDefault();
            e.stopPropagation();
        }
    }
}), { passive: false };

//接受所有输入框的快捷键(因为我们的输入框不多,如果输入框要避免响应,那么必须监听键盘按下事件,并且阻止默认和防止冒泡)
// hotkeys.filter = e => true;//我们将在inputhint中修改这个

window.onload = function ()
{
    let el = document.getElementById("loader-wrapper");
    el.remove();
    function isWebGLAvailable()
    {
        try
        {
            var canvas = document.createElement('canvas');
            return !!(globalThis.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
        }
        catch (e)
        {
            return false;
        }
    }
    const { detect } = require('detect-browser');
    function CheckVer()
    {
        try
        {
            const browser = detect();
            if (browser.name === "chrome" || browser.name === "edge-chromium")
            {
                let ver = parseInt(browser.version.split(".")[0]);
                return ver > 85;
            }
        } catch (error)
        {
        }
        return false;
    }

    if (!isWebGLAvailable() || !CheckVer())
    {
        document.body.innerText = "您的浏览器版本过低!";
        document.body.style.cssText = `
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30px;
        flex-direction: column;
        `;
        let herfEl = document.createElement("a");
        herfEl.innerText = "点击下载谷歌浏览器!";
        let linkUrl = "https://www.google.cn/chrome/";
        herfEl.href = linkUrl;
        document.body.append(herfEl);
        window.open(linkUrl);
        return;
    }

    if (window.location.hostname === "t.cfcad.cn")
        AppToaster.show({
            message: "这个环境仅供测试使用!!!请勿在生产中使用这个地址,否则将产生错误图纸或者无法打开的图纸!!!(本地址仅供测试账号使用,数据随时清空)",
            timeout: 15000,
            intent: Intent.WARNING,
        });
    else if (window.location.pathname === "/dev/")
        AppToaster.show({
            message: "这个环境仅供测试使用!!!请勿在生产中使用这个地址,否则将产生错误图纸或者无法打开的图纸!!!",
            timeout: 15000,
            intent: Intent.WARNING,
        });
    else if (window.location.hostname === "localhost")
        ReportErrorWrap.IsProduction = false;
    else
        ReportErrorWrap.IsProduction = true;

    Object3D.DefaultMatrixAutoUpdate = false;

    Layers.prototype.test = (layers) => true;
    new ErrorMonitoring();

    LogEnable.Display = true;

    ReportErrorWrap.ReportError = ReportError;

    HostApplicationServices.LoadDefaultExr = LoadDefaultExr;
    HostApplicationServices.LoadMetalEnv = LoadMetalEnv;

    HostApplicationServices.ProxyObject = userConfig;

    new WebCAD();

    LoadDefaultExr();
};

globalThis["copy"] = (text: string) =>
{
    console.log("你有2秒的时间让页面聚焦,否则将无法拷贝!");
    setTimeout(async () =>
    {
        await copyTextToClipboard(text);
        console.log("拷贝成功!");
    }, 2000);
};
