import {
    Matrix4,
	Mesh,
	PlaneGeometry,
    MeshBasicMaterial,
    Vector3,
} from 'three';

import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';

class Particles {
    constructor(engine, data) {
        const { x, y, count, w, h } = data;
        let positions = Particles.positions(count, w, h);
        return new Promise(async (resolve, reject) => {
            let t = await engine.loadTexture(data.$go.asset.name)
            var geometry = new PlaneGeometry(x || 1, y || 1);
            var material = new MeshBasicMaterial({
                map: t,
                alphaTest: 0.5
            });
            geometry.applyMatrix4(new Matrix4().makeTranslation(0, geometry.parameters.height / 2, 0));
            geometry.normalizeNormals();

            var arr = [];
            for (var i = 0; i < positions.length; i++) {
                var position = positions[i];
                var baseAngle = Math.PI * 2 * Math.random();

                var nPlanes = 2;
                for (var j = 0; j < nPlanes; j++) {
                    var angle = baseAngle + j * Math.PI / nPlanes;
                    var gg = geometry.clone();
                    gg.rotateY(angle);
                    gg.translate(position.x, position.y, position.z);
                    arr.push(gg);

                    gg = geometry.clone();
                    gg.rotateY(angle + Math.PI);
                    gg.translate(position.x, position.y, position.z);
                    arr.push(gg);
                }
            }
            this.object = new Mesh(BufferGeometryUtils.mergeGeometries(arr, false), material);
            resolve(this);
            arr.forEach(g => g.dispose());
        });
    }
    static positions(count, x, z) {
        let positions = new Array(count);
        for (var i = 0; i < count; i++) {
            var position = new Vector3();
            position.x = (Math.random() - 0.5) * x;
            position.z = (Math.random() - 0.5) * z;
            positions[i] = position;
        }
        return positions;
    }
}


export { Particles }