var camera, cameraOrtho, scene, sceneOrtho, renderer, orbitCtl, cube, distance;
var width, height, depth;
var languageContent;

initPage();



function initPage() {
    //version: 1320
    // 解析的url后缀 e.g.:
    // ?={"Load":"加载中...","RotateR":"旋转-","RotateL":"旋转+","Move":"移动","Clip":"切割","QuickClip":"AI切割","Delete":"删除","Reset":"重置"}
    // let url = location.href;
    // let language = decodeURI(
    //   url.substr(url.indexOf("=") + 1, url.length - url.indexOf("="))
    // );
    // console.log(language);
    // languageContent = JSON.parse(language);
    if (isCurrentChinese) {
        languageContent = {
            Load: "加载中...",
            RotateR: "旋转-",
            RotateL: "旋转+",
            Move: "移动",
            Clip: "切割",
            QuickClip: "AI切割",
            Delete: "删除",
            Reset: "重置",
        };
    } else {
        languageContent = {
            Load: "Loading...",
            RotateR: "Rotate-",
            RotateL: "Rotate+",
            Move: "Move",
            Clip: "Clip",
            QuickClip: "AIClip",
            Delete: "Delete",
            Reset: "Reset",
        };
    }


    var text = document.getElementById("loadText");
    text.innerHTML = languageContent.Load;
    var infoText = document.getElementById("infoText");
    infoText.innerHTML = languageContent.QuickClipFail;
    OSHelper.init();
    scene = new THREE.Scene();
    sceneOrtho = new THREE.Scene();
    scene.add(new THREE.AmbientLight(0xffffff));
    // Renderer
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setClearColor(0x464646, 1.0);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.autoClear = false;
    window.addEventListener("resize", onWindowResize, false);
    document.body.appendChild(renderer.domElement);
    renderer.localClippingEnabled = true;
    SpriteManager.init();
    LinesDrawingManager.initLine();
    // Controls
    camera = new THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        20,
        20000
    );
    //camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 20, 20000);
    camera.up.set(0, 0, 1);

    cameraOrtho = new THREE.OrthographicCamera(
        -window.innerWidth / 2,
        window.innerWidth / 2,
        window.innerHeight / 2,
        -window.innerHeight / 2,
        1,
        10
    );
    cameraOrtho.position.z = 10;

    orbitCtl = new THREE.OrbitControls(camera, renderer.domElement);
    orbitCtl.enablePan = false;
    animate();
    initClipArgs();
    // 触发方式 setSurface(100,100,100,"../3DWeb/FaceImage")
    EventCenter.addEventHandler("SetSurface", createCube);
    EventCenter.addEventHandler("ChangeSurface", changeCube);
    EventCenter.addEventHandler("AdjustedCubeImage", adjustedCubeImage);
    EventCenter.addEventHandler("RemoveCube", removeCube);
}

function createCube(surfaceInfo) {
    SpriteManager.allowClip = false;
    //remove old
    removeCube();

    //create new
    width = surfaceInfo.cubeWidth;
    height = surfaceInfo.cubeHeight;
    depth = surfaceInfo.cubeDepth;

    let surfacePaths = [];
    for (let i = 1; i <= 6; i++) {
        surfacePaths.push(surfaceInfo.surfaceFolder + "/" + i + ".jpg");
    }

    let materials = [];
    let textures = loadSurface(surfacePaths);
    textures.forEach((texture) => {
        materials.push(
            //   new THREE.MeshPhongMaterial({ map: texture, clippingPlanes: [] })
            ShaderMaterialHelper(texture, [])
        );
    });
    let geometry = new THREE.BoxGeometry(width, height, depth);
    cube = new THREE.Mesh(geometry, materials);
    cube.position.set(width / 2, height / 2, -depth / 2);
    scene.add(cube);
    resetCubePosition();
    EdgesManager.edgesNeedUpdate = true;
}

function changeCube(surfaceInfo) {
    SpriteManager.allowClip = false;
    //remove old
    removeCube();
    //create new
    width = surfaceInfo.cubeWidth;
    height = surfaceInfo.cubeHeight;
    depth = surfaceInfo.cubeDepth;
    let surfacePaths = [];
    for (const surface of surfaceInfo.surfacesList) {
        surfacePaths.push(surface);
    }

    let materials = [];
    let textures = loadBase64Surface(surfacePaths);
    textures.forEach((texture) => {
        materials.push(
            //   new THREE.MeshPhongMaterial({ map: texture, clippingPlanes: [] })
            ShaderMaterialHelper(texture, [])
        );
    });
    let geometry = new THREE.BoxGeometry(width, height, depth);
    cube = new THREE.Mesh(geometry, materials);
    cube.position.set(width / 2, height / 2, -depth / 2);
    scene.add(cube);
    resetCubePosition();
    EdgesManager.edgesNeedUpdate = true;
}

// 调整立方体六个面的参数
function adjustedCubeImage(params) {
    if (cube != undefined) {
        for (let i = 0; i < 6; i++) {
            cube.material[i].uniforms.fSharpness.value = params[0];
            cube.material[i].uniforms.fBrightness.value = params[1];
            cube.material[i].uniforms.fContrast.value = params[2];
        }
    }
}

function removeCube() {
    if (cube != undefined) {
        SpriteManager.waitMdlFileLoading();
        SpriteManager.resetChecked();
        cube.material.forEach((material) => {
            if (material.uniforms.tDiffuse.value != undefined) {
                material.uniforms.tDiffuse.value.dispose();
            }
            material.dispose();
        });
        cube.geometry.dispose();
        scene.remove(cube);
    }
}
function resetCubePosition() {
    camera.position.set(width * 1.2, -width * 1.8, depth / 2);
    orbitCtl.target = cube.position;
    orbitCtl.update();
    orbitCtl.maxDistance = width * OSHelper.orbitCtlDistanceMultiple;
    orbitCtl.minDistance = width * (OSHelper.orbitCtlDistanceMultiple - 1);
}

function loadSurface(images, callback) {
    var textures = [];
    for (let i = 0; i < images.length; i++) {
        textures[i] = LoaderUtility.loadUniqueTexture(images[i], (texture) => {
            texture.minFilter = texture.magFilter = THREE.LinearFilter;
            texture.mapping = THREE.UVMapping;
            texture.center.set(0.5, 0.5);
            if (i === 0) {
                texture.rotation = 1.57;
            }
            if (i === 1) {
                texture.rotation = -1.57;
            }
            if (i === 5) {
                texture.rotation = 3.14;
            }

            if (callback != undefined) {
                callback(texture, i);
            }
        });
    }

    return textures;
}
function loadBase64Surface(images, callback) {
    var textures = [];
    for (let i = 0; i < images.length; i++) {
        textures[i] = LoaderUtility.loadBase64Texture(images[i], (texture) => {
            texture.minFilter = texture.magFilter = THREE.LinearFilter;
            texture.mapping = THREE.UVMapping;
            texture.center.set(0.5, 0.5);
            if (i === 0) {
                texture.rotation = 1.57;
            }
            if (i === 1) {
                texture.rotation = -1.57;
            }
            if (i === 5) {
                texture.rotation = 3.14;
            }

            if (callback != undefined) {
                callback(texture, i);
            }
        });
    }

    return textures;
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    cameraOrtho.left = -window.innerWidth / 2;
    cameraOrtho.right = window.innerWidth / 2;
    cameraOrtho.top = window.innerHeight / 2;
    cameraOrtho.bottom = -window.innerHeight / 2;
    cameraOrtho.updateProjectionMatrix();
    SpriteManager.resetSpritePosition();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
    renderer.clear();
    renderer.render(scene, camera);
    renderer.clearDepth();
    renderer.render(sceneOrtho, cameraOrtho);
    requestAnimationFrame(animate);
}
