window.InputClick = (elementId) => {
    document.getElementById(elementId).click();
}

window.DownloadImage = (url, fileName) => {
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

window.DownloadImageBase64 = (base64Data, fileName) => {
    // Chuyển đổi Base64 thành Blob
    const byteCharacters = atob(base64Data.split(',')[1]);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    const blob = new Blob([byteArray], { type: 'image/png' }); // Thay đổi type nếu cần

    // Tạo Object URL từ Blob
    const url = URL.createObjectURL(blob);

    // Tạo thẻ `<a>` để tải về
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // Giải phóng bộ nhớ
    URL.revokeObjectURL(url);
}

window.setCssVariable = (variable, value) => {
    document.documentElement.style.setProperty(variable, value);
    localStorage.setItem(variable, value);
};

window.getCssVariable = (variable) => {
    return localStorage.getItem(variable);
};

window.DOMCssLoaded = () => {
    const width = localStorage.getItem('--edge-stroke-width');
    if (width) {
        document.documentElement.style.setProperty('--edge-stroke-width', width);
    }
    else {
        document.documentElement.style.setProperty('--edge-stroke-width', "0.15px");
    }

    const directionwidth = localStorage.getItem('--edge-direction-stroke-width');
    if (directionwidth) {
        document.documentElement.style.setProperty('--edge-direction-stroke-width', directionwidth);
    }
    else {
        document.documentElement.style.setProperty('--edge-direction-stroke-width', "0.3px");
    }

    const radius = localStorage.getItem('--node-r');
    if (radius) {
        document.documentElement.style.setProperty('--node-r', radius);
    }
    else {
        document.documentElement.style.setProperty('--node-r', "0.1px");
    }

    const originwidth = localStorage.getItem('--origin-vector-stroke-width');
    if (originwidth) {
        document.documentElement.style.setProperty('--origin-vector-stroke-width', originwidth);
    }
    else {
        document.documentElement.style.setProperty('--origin-vector-stroke-width', "0.35px");
    }
};

window.UpdateViewContainerRect = async (dotnetRef, divElement, funcName) => {
    var rect = divElement.getBoundingClientRect();
    await dotnetRef.invokeMethodAsync(funcName, rect.x, rect.y, rect.width, rect.height, rect.top, rect.right, rect.bottom, rect.left);
};

window.ResizeObserverRegister = (dotnetRef, divElement, funcName) => {
    const resizeObserver = new ResizeObserver(async (entries) => {
        await window.UpdateViewContainerRect(dotnetRef, divElement, funcName);
    });

    resizeObserver.observe(divElement);
};

window.AddEventListener = (dotnetRef, element, eventName, funcName, stopPropagation = true) => {
    element.addEventListener(eventName, async (ev) => {
        ev.preventDefault();
        if (stopPropagation) ev.stopPropagation();
        await dotnetRef.invokeMethodAsync(funcName);
    })
};

window.AddMouseMoveEventListener = (dotnetRef, element, funcName, stopPropagation = true) => {
    element.addEventListener("mousemove", async (ev) => {
        ev.preventDefault();
        if (stopPropagation) ev.stopPropagation();
        await dotnetRef.invokeMethodAsync(funcName, ev.clientX, ev.clientY, ev.buttons, ev.ctrlKey, ev.movementX, ev.movementY);
    })
};

window.AddKeyUpEventListener = (dotnetRef, element, funcName, stopPropagation = true) => {
    element.addEventListener("keyup", async (ev) => {
        if (stopPropagation) ev.stopPropagation();
        await dotnetRef.invokeMethodAsync(funcName, ev.code, ev.key, ev.altKey, ev.ctrlKey, ev.shiftKey);
    })
};

window.AddMouseWheelEventListener = (dotnetRef, element, funcName, stopPropagation = true) => {
    element.addEventListener("mousewheel", async (ev) => {
        if (stopPropagation) ev.stopPropagation();
        await dotnetRef.invokeMethodAsync(funcName, ev.deltaY, ev.offsetX, ev.offsetY);
    }, { passive: true })
};

window.AddMouseUpEventListener = (dotnetRef, element, funcName, stopPropagation = true) => {
    element.addEventListener("mouseup", async (ev) => {
        ev.preventDefault();
        if (stopPropagation) ev.stopPropagation();
        await dotnetRef.invokeMethodAsync(funcName, ev.button, ev.altKey, ev.ctrlKey, ev.shiftKey);
    })
};

window.AddMouseDownEventListener = (dotnetRef, element, funcName, stopPropagation = true) => {
    element.addEventListener("mousedown", async (ev) => {
        ev.preventDefault();
        if (stopPropagation) ev.stopPropagation();
        await dotnetRef.invokeMethodAsync(funcName, ev.button, ev.altKey, ev.ctrlKey, ev.shiftKey);
    })
};

window.SetMapSvgConfig = (element, width, height, originX, originY) => {
    if (element && element.nodeName && element.nodeName.toLowerCase() === "svg") {
        element.setAttribute("width", width );
        element.setAttribute("height", height );
        element.setAttribute("viewBox", `${originX} ${originY} ${width} ${height}`);
    }
};

window.SetMapSvgRect = (element, width, height) => {
    if (element && element.nodeName && element.nodeName.toLowerCase() === "svg") {
        element.setAttribute("width", width);
        element.setAttribute("height", height);
    }
};

window.SetImageAttribute = (element, width, height, originX, originY, href) => {
    if (element && element.nodeName && element.nodeName.toLowerCase() === "image") {
        element.setAttribute("width", width );
        element.setAttribute("height", height );
        element.setAttribute("x", originX);
        element.setAttribute("y", originY);
        element.setAttribute("href", href);
    }
};

window.SetMapMovement = (element, top, left) => {
    if (element && element.nodeName && element.nodeName.toLowerCase() === "div") {
        element.setAttribute("style", `top: ${top}px; left: ${left}px;`);
    }
};

window.SetMapScale = (element, scale) => {
    if (element && element.nodeName && element.nodeName.toLowerCase() === "div") {
        element.setAttribute("style", `transform: scale(${scale });`);
    }
};

window.SetNodePosition = (circleRef, textRef, x, y) => {
    if (circleRef && circleRef.setAttribute) {
        circleRef.setAttribute("cx", x);
        circleRef.setAttribute("cy", y);
    }
    if (textRef && textRef.setAttribute) {
        const radius = parseFloat(localStorage.getItem('--node-r'));
        if (!radius) {
            radius = 0.1;
        }
        textRef.setAttribute("x", x);
        textRef.setAttribute("y", - y - radius - 0.08);
    }
};

window.AddSelected = (element) => {
    element.classList.add("active");
};

window.RemoveSelected = (element) => {
    element.classList.remove("active");
};

window.ElementSetAttribute = (element, attr, value) => {
    if (element && element.setAttribute) element.setAttribute(attr, value);
}

window.AddTouchMoveEventListener = (dotnetRef, element, funcName, stopPropagation = true) => {
    let lastX = 0, lastY = 0;
    element.addEventListener("touchmove", async (ev) => {
        ev.preventDefault();
        if (stopPropagation) ev.stopPropagation();

        const touch = ev.touches[0];
        const movementX = touch.clientX - lastX;
        const movementY = touch.clientY - lastY;

        lastX = touch.clientX;
        lastY = touch.clientY;
        await dotnetRef.invokeMethodAsync(funcName, touch.clientX, touch.clientY, ev.touches.length, movementX, movementY);
    });

    element.addEventListener("touchstart", (ev) => {
        const touch = ev.touches[0];
        lastX = touch.clientX;
        lastY = touch.clientY;
    });
};

window.DownloadMap = async (filename, content) => {
    const arrayBuffer = await content.arrayBuffer();
    const blob = new Blob([arrayBuffer]);
    const url = URL.createObjectURL(blob);

    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = filename;
    anchor.click();

    URL.revokeObjectURL(url);
}

window.SetElementPosition = (robotRef, nameRef, x, y, theta, originX, originY) => {
    if (robotRef && robotRef.setAttribute) {
        robotRef.setAttribute("x", x + originX);
        robotRef.setAttribute("y", y + originY);
        robotRef.setAttribute("transform", `rotate(${theta} ${x} ${y})`);
    }
    if (nameRef && nameRef.setAttribute) {
        nameRef.setAttribute("x", x);
        nameRef.setAttribute("y", -y);
    }
}

window.ScrollToBottom = (objDiv) => {
    if (objDiv.scrollTop != objDiv.scrollHeight) {
        objDiv.scrollTop = objDiv.scrollHeight;
    }
}