#include <cfloat>
#include "TreeNode.hpp"

namespace nbody {
	using namespace std;


	TreeNode::TreeNode() {
		for (int i = 0; i < 3; i++) {
			this->bb.min[i] = 1.0;
			this->bb.max[i] = -1.0;
		}
		this->afterMySubtree = NULL;
	}

	TreeNode::~TreeNode() {
	}

	Box TreeNode::getBB() {
		return this->bb;
	}

	bool TreeNode::isSplitable() {
		if (this->bodies.size() < 2) {
			return false;
		}
		for (int i = 0; i < 3; i++) {
			if (this->bb.max[i] - this->bb.min[i] < FLT_MIN) {
				return false;
			}
		}
		return true;
	}

	void TreeNode::extendBBforBodies() {
		if (this->bodies.empty()) return;
		for (int i = 0; i < 3; i++) {
			this->bb.min[i] = this->bodies.front().getPosition(i);
			this->bb.max[i] = this->bodies.front().getPosition(i);
		}
		for (vector<Body>::iterator it = this->bodies.begin(); it != this->bodies.end(); it++) {
			for (int i = 0; i < 3; i++) {
				if (it->getPosition(i) < this->bb.min[i]) {
					this->bb.min[i] = it->getPosition(i);
				}
				if (it->getPosition(i) > this->bb.max[i]) {
					this->bb.max[i] = it->getPosition(i);
				}
			}
		}
	}

	void TreeNode::extendBBtoCube() {
		this->bb.extendToCube();
	}

	vector<Body> TreeNode::getBodies() {
		return this->bodies;
	}
}
