import { Mesh } from './Mesh';
import { Texture } from '../texture';

/**
 * The Plane allows you to draw a texture across several points and them manipulate these points
 *
 *```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new Point(i * 50, 0));
 * };
 * let Plane = new Plane(Texture.fromImage("snake.png"), points);
 *  ```
 *
 * @class
 * @extends Mesh
 *
 */
export class Plane extends Mesh {
    verticesX: number;
    verticesY: number;
    /**
     * @param {Texture} texture - The texture to use on the Plane.
     * @param {number} [verticesX=10] - The number of vertices in the x-axis
     * @param {number} [verticesY=10] - The number of vertices in the y-axis
     */
    constructor(texture: Texture, verticesX: number = 10, verticesY: number = 10) {
        super(texture);
        this.verticesX = verticesX || 10;
        this.verticesY = verticesY || 10;
        this.refresh();
    }

    /**
     * Refreshes plane coordinates
     *
     */
    _refresh() {
        const texture = this.texture;
        const total = this.verticesX * this.verticesY;
        const verts = [];
        const uvs = [];
        const indices = [];

        const segmentsX = this.verticesX - 1;
        const segmentsY = this.verticesY - 1;

        const sizeX = texture.width / segmentsX;
        const sizeY = texture.height / segmentsY;

        for (let i = 0; i < total; i++) {
            const x = (i % this.verticesX);
            const y = ((i / this.verticesX) | 0);

            verts.push(x * sizeX, y * sizeY);

            uvs.push(x / segmentsX, y / segmentsY);
        }



        // console.log(indices)
        this._vertices = new Float32Array(verts);
        this._uvs = new Float32Array(uvs);
        this._indices = calculatePlaneIndices(this.verticesX,this.verticesY);

        this._vertexDirty++;

        this.multiplyUvs();
    }
}

/**
 * 计算平面的索引
 * @param verticesX x轴上的顶点数量，最小2
 * @param verticesY y轴上的顶点数量，最小2
 */
export function calculatePlaneIndices(verticesX: number, verticesY: number): Uint16Array {
    const segmentsX = verticesX - 1;
    const segmentsY = verticesY - 1;
    const totalSub = segmentsX * segmentsY;
    const indices = [];
    for (let i = 0; i < totalSub; i++) {
        const xpos = i % segmentsX;
        const ypos = (i / segmentsX) | 0;

        const value = (ypos * verticesX) + xpos;
        const value2 = (ypos * verticesX) + xpos + 1;
        const value3 = ((ypos + 1) * verticesX) + xpos;
        const value4 = ((ypos + 1) * verticesX) + xpos + 1;

        indices.push(value, value2, value3);
        indices.push(value2, value4, value3);
    }
    return new Uint16Array(indices);
}
