#include "ofxBox2dLoop.h"

ofxBox2dLoop::ofxBox2dLoop() {
    m_vertices = NULL;
}

//ofxBox2dLoop::~ofxBox2dLoop() { }

bool ofxBox2dLoop::createShape(b2World* world, bool staticBody) {
    destroyShape();

    int numVerts = vertices.size();

    if (numVerts <= 2) {
        return false;
    }

    m_world = world;

	b2BodyDef bd;
	bd.position.Set(0.0f, 0.0f);
	if (!staticBody) {
	    bd.type = b2_dynamicBody;
	}
	m_body = m_world->CreateBody(&bd);


    delete [] m_vertices;
    m_vertices = new b2Vec2[numVerts];

	for(int i=0; i<numVerts; i++) {
        m_vertices[i].Set(vertices[i].x/OFX_BOX2D_SCALE, vertices[i].y/OFX_BOX2D_SCALE);
    }

	b2LoopShape loop;
    loop.m_vertices = m_vertices;
    loop.m_count = numVerts;

	b2FixtureDef fd;
	fd.shape = &loop;
	fd.density = 0.0f;
	fd.restitution = 0.1f;
	fd.friction = 0.6f;

	m_body->CreateFixture(&fd);

    return true;
}

void ofxBox2dLoop::clear() {
    vertices.clear();
}

void ofxBox2dLoop::addVertex(float x, float y) {
    ofPoint p;
    p.x = x;
    p.y = y;
    vertices.push_back(p);
}

void ofxBox2dLoop::draw() {
    if (m_body) {
        b2LoopShape* loop = (b2LoopShape*)m_body->GetFixtureList()->GetShape();
        b2Vec2 p = m_body->GetPosition();
        p *= OFX_BOX2D_SCALE;

        glPushMatrix();
        glTranslatef(p.x, p.y, 0.0f);

        if (a < 255) { ofEnableAlphaBlending(); }
        ofColor prevCol = ofGetStyle().color;
        ofSetColor(r, g, b, a);

        ofBeginShape();
        for (int i=0; i<loop->m_count; i++) {
            ofVertex(loop->m_vertices[i].x * OFX_BOX2D_SCALE, loop->m_vertices[i].y * OFX_BOX2D_SCALE);
        }
        ofVertex(loop->m_vertices[0].x * OFX_BOX2D_SCALE, loop->m_vertices[0].y * OFX_BOX2D_SCALE);
        ofEndShape();

        ofSetColor(prevCol.r, prevCol.g, prevCol.b, prevCol.a);
        if (a < 255) { ofDisableAlphaBlending(); }

        glPopMatrix();
    }
}
