package client.renderer.model;

import org.lwjgl.opengl.GL11;

import client.renderer.DefaultVertexFormats;
import client.renderer.RenderBuffer;
import client.renderer.Tessellator;
import common.util.Vec3;

public class TexturedQuad
{
    public final PositionTextureVertex[] vertices = new PositionTextureVertex[4];

    public TexturedQuad(Vec3 u2v1, Vec3 u1v1, Vec3 u1v2, Vec3 u2v2, float u1, float v1, float u2, float v2, float tw, float th)
    {
//        float ax = 0.0F / tw;
//        float ay = 0.0F / th;
//        this.vertices[0] = u2v1.toTextureVertex(u2 / tw - ax, v1 / th + ay);
//        this.vertices[1] = u1v1.toTextureVertex(u1 / tw + ax, v1 / th + ay);
//        this.vertices[2] = u1v2.toTextureVertex(u1 / tw + ax, v2 / th - ay);
//        this.vertices[3] = u2v2.toTextureVertex(u2 / tw - ax, v2 / th - ay);
        this.vertices[0] = new PositionTextureVertex(u2v1, u2 / tw, v1 / th);
        this.vertices[1] = new PositionTextureVertex(u1v1, u1 / tw, v1 / th);
        this.vertices[2] = new PositionTextureVertex(u1v2, u1 / tw, v2 / th);
        this.vertices[3] = new PositionTextureVertex(u2v2, u2 / tw, v2 / th);
    }

    public TexturedQuad(Vec3[] verts, int[] uvs, float tw, float th)
    {
        this(verts[0], verts[1], verts[2], verts[3], uvs[0], uvs[1], uvs[2], uvs[3], tw, th);
    }

    public TexturedQuad(Vec3[] verts, float u1, float v1, float u2, float v2, float tw, float th)
    {
        this(verts[0], verts[1], verts[2], verts[3], u1, v1, u2, v2, tw, th);
    }

    public void flipFace()
    {
        PositionTextureVertex[] vertices = new PositionTextureVertex[this.vertices.length];
        for (int i = 0; i < this.vertices.length; ++i)
        {
            vertices[i] = this.vertices[this.vertices.length - i - 1];
        }
        System.arraycopy(vertices, 0, this.vertices, 0, this.vertices.length);
    }
    
    public void addTo(RenderBuffer renderer, float scale)
    {
        Vec3 norma = this.vertices[1].pos.subtractReverse(this.vertices[0].pos);
        Vec3 normb = this.vertices[1].pos.subtractReverse(this.vertices[2].pos);
        Vec3 norm = normb.crossProduct(norma).normalize();
        float nx = (float)norm.xCoord;
        float ny = (float)norm.yCoord;
        float nz = (float)norm.zCoord;
//        if (this.invNorm)
//        {
//            nx = -nx;
//            ny = -ny;
//            nz = -nz;
//        }
        renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.OLDMODEL_POSITION_TEX_NORMAL);
        for (int i = 0; i < 4; ++i)
        {
            PositionTextureVertex vertex = this.vertices[i];
            renderer.pos(vertex.pos.xCoord * (double)scale, vertex.pos.yCoord * (double)scale, vertex.pos.zCoord * (double)scale)
            		.tex((double)vertex.texX, (double)vertex.texY).normal(nx, ny, nz).endVertex();
        }
//        Tessellator.getInstance();
		Tessellator.draw();
    }
}
