#include "BarnesHutTree.hpp"
#include "Node.hpp"
#include <iostream>

namespace nbody {
	using namespace std;

	BarnesHutTree::BarnesHutTree() {
	}

	BarnesHutTree::~BarnesHutTree() {
	}

	vector<Box> BarnesHutTree::splitBB(Node* node) {
		return node->getBB().octreeSplit();
	}

	int BarnesHutTree::numberOfChildren() {
		return 8;
	}

	void BarnesHutTree::build(vector<Body> bodies) {
		Node* current;

		this->clean();
		if (bodies.empty()) return;
		//insert root node
		this->nodes->insertAfter(new Node(this));
		current = this->nodes->next;
		//assign bodies to root node
		current->bodies = bodies;
		//setup proper bounding box
		current->extendBBforBodies();
		current->extendBBtoCube();
		current->afterSubtree = current->next;

		//iterate over existing boxes and split if it contains too much bodies
		while (current != this->nodes) {
			if (current->isSplitable()) {
				vector<Box> subboxes = this->splitBB(current);
				current->leaf = false;

				for (vector<Box>::iterator it = subboxes.begin(); it != subboxes.end(); it++) {
					Node* child = new Node(this);

					child->parent = current;
					child->bb = *it;
					child->bodies = it->copyBodies(current->bodies);
					current->insertAfter(child);
					child->nextSibling = current->next;
					current->next->prevSibling = child;
					if (it != subboxes.begin()) {
						child->afterSubtree = child->next;
					} else {
						child->afterSubtree = current->afterSubtree;
					}
				}
				current->bodies.clear();
			}
			current = current->next;
		}
		/*
		//iterate for updating representatives
		current = this->nodes->prev;
		while (current != this->nodes) {
			current->representative.mass = 0.0;
			current->representative.position[0] = 0.0;
			current->representative.position[1] = 0.0;
			current->representative.position[2] = 0.0;
			if (current->leaf) {
				for (unsigned int i = 0; i < current->bodies.size(); i++) {
					current->representative.mass += current->bodies[i].mass;
					for (int j = 0; j < 3; j++) {
						current->representative.position[j] += current->bodies[i].position[j];
					}
				}
			} else {
				Node* child = current->next;

				do {
					current->representative.mass += child->representative.mass;
					for (int j = 0; j < 3; j++) {
						current->representative.position[j] += child->representative.position[j];
					}
					child = child->nextSibling;
				} while (child != NULL);
			}
			current->representative.mass /= current->bodies.size();
			for (int j = 0; j < 3; j++) {
				current->representative.position[j] /= current->bodies.size();
			}
			current = current->prev;
		}
		*/
	}
}
