import { TextureAttachmentsByMaterialType } from "../../../asset/loaders/material/TextureAttachmensByMaterialType.js";
import { max2 } from "../../../../core/math/max2.js";
import { BUFFER_GEOMETRY_UVS } from "./BUFFER_GEOMETRY_UVS.js";

/**
 * Is this mesh qualified to be optimized?
 * @param {THREE.Mesh} mesh
 * @returns {boolean}
 */
export function is_compliant_mesh(mesh) {
    const material = mesh.material;

    const attachments = TextureAttachmentsByMaterialType[material.type];

    const uv_scales = [1, 1, 1, 1];

    const texture_attachment_count = attachments.length;

    for (let i = 0; i < texture_attachment_count; i++) {
        const attachment = attachments[i];

        const texture = attachment.read(material);
        if (texture === undefined || texture === null) {
            continue;
        }

        const uv_index = attachment.uv_index;

        uv_scales[uv_index * 2] = max2(uv_scales[uv_index * 2], texture.repeat.x)
        uv_scales[uv_index * 2 + 1] = max2(uv_scales[uv_index * 2 + 1], texture.repeat.y)
    }

    const geometry = mesh.geometry;

    for (let i = 0; i < BUFFER_GEOMETRY_UVS.length; i++) {
        const uv_metadata = BUFFER_GEOMETRY_UVS[i];

        /**
         *
         * @type {THREE.BufferAttribute }
         */
        const attribute = geometry.attributes[uv_metadata.name];

        if (attribute === undefined) {
            continue;
        }

        const attribute_data = attribute.array;
        const n = attribute_data.length;

        const uv_index = uv_metadata.index;
        const uv_index_2 = uv_index * 2;

        for (let j = 0; j < n; j += 2) {
            const x = attribute_data[j];
            const y = attribute_data[j + 1];

            const scaled_u = x * uv_scales[uv_index_2];
            const scaled_v = y * uv_scales[uv_index_2 + 1];

            if (scaled_u > 1 || scaled_u < 0 || scaled_v > 1 || scaled_v < 0) {
                // repeating/negative UV value
                return false;
            }

        }

    }

    return true;
}
