class Tracks
{
    static LENGTH = 120;

    constructor( engine , car , offsetX , offsetY )
    {
        this.engine = engine;
        this.car = car;

        this.vertexBuffer = new Sparrow.VBO( this.engine );
        this.uvBuffer = new Sparrow.VBO( this.engine );

        this.vao = new Sparrow.VAO( this.engine );
        this.vao.bind();
    
        this.engine.gl.enableVertexAttribArray( 0 );
        this.engine.gl.enableVertexAttribArray( 2 );
    
        this.vertexBuffer.bind();
        this.engine.gl.vertexAttribPointer( 0 , 2 , this.engine.gl.FLOAT , false , 0 , 0 );
        this.uvBuffer.bind();
        this.engine.gl.vertexAttribPointer( 2 , 2 , this.engine.gl.FLOAT , false , 0 , 0 );

        this.vertices = new Float32Array( 2*Tracks.LENGTH );
        this.uvs = new Float32Array( 2*Tracks.LENGTH );

        // this.texture = Sparrow.Texture.WHITE;
        var buffer = new Uint8Array( [ 255 , 255 , 255 , 80 ] );
        this.texture = Sparrow.Texture.createFromBuffer( this.engine , buffer , 1 , 1 , "tracks" );

        this.vertexBuffer.bind();
        this.vertexBuffer.bufferData( this.vertices , this.engine.gl.DYNAMIC_DRAW );

        this.uvBuffer.bind();
        this.uvBuffer.bufferData( this.uvs , this.engine.gl.DYNAMIC_DRAW );

        this.M_test = new mat4();
        this.v = new vec3( offsetX , offsetY , 0 );
    }

    reset()
    {
        for ( let i = 0 ; i < this.vertices.length ; ++i ) this.vertices[i] = 0;
        this.vertexBuffer.bind();
        this.vertexBuffer.bufferData( this.vertices , this.engine.gl.DYNAMIC_DRAW );
    }

    update( dt )
    {
        this.add();
    }

    add()
    {
        // copy everything down
        for ( let i = Tracks.LENGTH-1 ; i >= 0 ; --i )
        {
            this.vertices[(i+1)*2+0] = this.vertices[i*2+0];
            this.vertices[(i+1)*2+1] = this.vertices[i*2+1];
        }


        if ( this.car.b_drifting ) this.M_test.updateRotationZ( Math.PI-(this.car.angle+this.car.driftingAngleOffset) );
        else this.M_test.updateRotationZ( Math.PI-this.car.angle );
        var result = mat4.multiplyVec3( this.M_test , this.v );
        this.vertices[0] = -this.car.x-result.data[0];
        this.vertices[1] = -this.car.y-result.data[1];

        this.vertexBuffer.bind();
        this.vertexBuffer.bufferData( this.vertices , this.engine.gl.DYNAMIC_DRAW );

        // this.uvBuffer.bind();
        // this.uvBuffer.bufferData( this.uvs , this.engine.gl.DYNAMIC_DRAW );
    }

    draw()
    {
        this.vao.bind();

        if ( this.texture !== undefined )
        {
            this.texture.bind();
        }

        Sparrow.drawArrays( this.engine , this.engine.gl.LINE_STRIP , 0 , Tracks.LENGTH );
    }
}