#include "ofxBox2dCircle.h"

//ofxBox2dCircle::ofxBox2dCircle() { }

//ofxBox2dCircle::~ofxBox2dCircle() { }

void ofxBox2dCircle::createShape(b2World* world, float x, float y, float radius, bool staticBody) {
    destroyShape();

    m_world = world;
    m_radius = radius;
    b2Vec2 p(x / OFX_BOX2D_SCALE, y / OFX_BOX2D_SCALE);

	b2BodyDef bd;
	bd.position = p;
	bd.bullet = true;
	if (!staticBody) {
	    bd.type = b2_dynamicBody;
	}
	m_body = m_world->CreateBody(&bd);

	b2CircleShape circle;
	circle.m_radius = m_radius / OFX_BOX2D_SCALE;

	b2FixtureDef fd;
	fd.shape = &circle;
	fd.density = 10.0f;
	fd.restitution = 1.0f;
	fd.friction = 0.3f;

	b2Vec2 minV = p - b2Vec2(circle.m_radius, circle.m_radius);
	b2Vec2 maxV = p + b2Vec2(circle.m_radius, circle.m_radius);

	b2AABB aabb;
	aabb.lowerBound = minV;
	aabb.upperBound = maxV;

	m_body->CreateFixture(&fd);
}

float ofxBox2dCircle::getRadius(){
    if (m_body) {
        b2CircleShape* c = (b2CircleShape*)m_body->GetFixtureList()->GetShape();
        return c->m_radius * OFX_BOX2D_SCALE;
    }
    else{return 0.0f;}
}

b2Vec2 ofxBox2dCircle::getPosition(){
    if (m_body) {
        b2Vec2 p = m_body->GetPosition();
        p *= OFX_BOX2D_SCALE;
        return p;
    }
    else{b2Vec2 p;
    return p;}
}



void ofxBox2dCircle::draw() {
    if (m_body) {
        b2CircleShape* c = (b2CircleShape*)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);

        ofCircle(0.0f, 0.0f, c->m_radius * OFX_BOX2D_SCALE);

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

        glPopMatrix();
    }
}
