import { OctahedronBufferGeometry } from "three";
import Entity from "../../ecs/Entity.js";
import { Transform } from "../../ecs/transform/Transform.js";
import { ShadedGeometry } from "../ecs/mesh-v2/ShadedGeometry.js";
import { ShadedGeometryFlags } from "../ecs/mesh-v2/ShadedGeometryFlags.js";
import { SH3VisualisationMaterial } from "./shader/SH3VisualisationMaterial.js";

const geometry = new OctahedronBufferGeometry(1, 5);

/**
 *
 * @param {number[]} sh
 * @param {number} sh_offset
 * @param {boolean} shadow
 * @returns {ShadedGeometry}
 */
export function sh3_make_shaded_geometry(sh, sh_offset, shadow=true) {
    const mat = new SH3VisualisationMaterial();

    mat.fromArray(sh,sh_offset);

    const shadedGeometry = ShadedGeometry.from(geometry, mat);

    // prevent instanced rendering
    shadedGeometry.setFlag(ShadedGeometryFlags.DrawMethodLocked);

    shadedGeometry.writeFlag(ShadedGeometryFlags.ReceiveShadow, shadow);
    shadedGeometry.writeFlag(ShadedGeometryFlags.CastShadow, shadow);

    return shadedGeometry;
}

/**
 *
 * @param {number} [size]
 * @param {boolean} [shadow]
 * @param position
 * @param [position_offset]
 * @param sh
 * @param [sh_offset]
 * @param {Entity} [entity]
 * @return {Entity}
 */
export function visualise_spherical_harmonic_sphere({
                                                        size = 1,
                                                        shadow = false,
                                                        position,
                                                        position_offset = 0,
                                                        sh,
                                                        sh_offset = 0,
                                                        entity = new Entity()
                                                    }) {

    const shadedGeometry = sh3_make_shaded_geometry(sh, sh_offset, shadow);

    entity
        .add(Transform.fromJSON({
            position: {
                x: position[position_offset],
                y: position[position_offset + 1],
                z: position[position_offset + 2],
            },
            scale: size
        }))
        .add(shadedGeometry);

    return entity;
}
