#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include "Tree.hpp"
#include "Node.hpp"
#include "Simulation.hpp"

namespace nbody {
	Tree::Tree(int parallelId) {
		//insert dummy root node
		this->nodes = new Node(this);
		this->maxLeafBodies = 16;
		this->parallelId = parallelId;
		this->simulation = NULL;
	}

	Tree::~Tree() {
		this->clean();
		delete this->nodes;
	}

	void Tree::setSimulation(Simulation* simulation) {
		this->simulation = simulation;
	}

	void Tree::clean() {
		//remove all nodes; refresh dummy first node
		while (this->nodes->next != this->nodes) {
			Node* node = this->nodes->next;

			node->unlink();
			delete node;
		}
		delete this->nodes;
		this->nodes = new Node(this);
	}

	size_t Tree::numberOfNodes() {
		unsigned long nodes = 0;

		for (Node* node = this->nodes->next; node != this->nodes; node = node->next) {
			nodes++;
		}
		return nodes;
	}

	bool Tree::isCorrect() {
		Node* current = this->nodes->next;

		while (current != this->nodes) {
			if (!current->isCorrect()) {
				return false;
			}
			current = current->next;
		}
		return true;
	}

	//accumulate force from the whole local tree on parameter body
	void Tree::accumulateForceOnto(Body& body) {
		Node* n = this->nodes->next;

		resetAcceleration(body);
		while (n != this->nodes) {
			if (n->sufficientForBody(body)) {
				accumulateForceOntoBody(body, n->representative);
				n = n->afterSubtree;
			} else if (n->leaf) {
				for (std::vector<Body>::iterator it = n->bodies.begin(); it != n->bodies.end(); it++) {
					accumulateForceOntoBody(body, *it);
				}
				n = n->afterSubtree;
			} else {
				n = n->next;
			}
		}
	}

	//accumulate forces for whole tree (local particles)
	void Tree::computeForces() {
		for (Node* n = this->nodes->next; n != this->nodes; n = n->next) {
			if (n->leaf) {
				for (std::vector<Body>::iterator it = n->bodies.begin(); it != n->bodies.end(); it++) {
					if (!it->refinement) {
						this->accumulateForceOnto(*it);
					}
				}
			}
		}
	}

	//get local bodies for rebuildiong tree after moving particles
	std::vector<Body> Tree::extractLocalBodies() {
		std::vector<Body> result;

		while (this->nodes->next != this->nodes) {
			if (this->nodes->next->leaf) {
				for (std::vector<Body>::iterator it = this->nodes->next->bodies.begin(); it != this->nodes->next->bodies.end(); it++) {
					if (!it->refinement) {
						result.push_back(*it);
					}
				}
			}
			Node* h = this->nodes->next;
			this->nodes->next->unlink();
			delete(h);
		}
		this->clean();
		return result;
	}

	//get refinement particles required to compute forces within remote domains
	std::vector<Body> Tree::copyRefinements(Box domain) {
		std::vector<Body> result;
		Node* current = this->nodes->next;

		if (!isValid(current->bb)) {
			//empty tree means no refinements
			return result;
		}
		while (current != this->nodes) {
			bool sufficient = current->sufficientForBox(domain);

			if (sufficient) {
				if (current->representative.mass > 0.0) {
					result.push_back(current->representative);
				}
				current = current->afterSubtree;
			} else if (current->leaf) {

				result.insert(result.end(), current->bodies.begin(), current->bodies.end());
				current = current->next;
			} else {
				current = current->next;
			}
		}
		return result;
	}

	//get bounding box of root node
	Box Tree::getRootBB() {
		return this->nodes->next->bb;
	}

	//rebuild with predefined root node bounding box
	void Tree::rebuild(Box domain) {
		this->build(this->extractLocalBodies(), domain);
	}

	void Tree::rebuild() {
		this->build(this->extractLocalBodies());
	}

	//rebuild with predefined root node bounding box and bodies
	void Tree::rebuild(Box domain, std::vector<Body> bodies) {
		this->build(bodies, domain);
	}

	//move particles according to accumulated forces
	Box Tree::advance() {
		Box bb;

		for (Node* n = this->nodes->next; n != this->nodes; n = n->next) {
			if (n->leaf) {
				for (std::vector<Body>::iterator it = n->bodies.begin(); it != n->bodies.end(); it++) {
					if (!it->refinement) {
						double pos[3] = {it->position[0], it->position[1], it->position[2]};
						integrate(*it);
						extend(bb, *it);
					}
				}
			}
		}
		return bb;
	}

	//determine local tree bounding box
	Box Tree::getLocalBB() {
		Box result;

		initBox(result);
		for (Node* n = this->nodes->next; n != this->nodes; n = n->next) {
			if (n->leaf) {
				for (std::vector<Body>::iterator it = n->bodies.begin(); it != n->bodies.end(); it++) {
					if (!it->refinement) {
						extend(result, *it);
					}
				}
			}
		}
		return result;
	}

	void Tree::print(int parallelId) {
		for (Node* n = this->nodes->next; n != this->nodes; n = n->next) {
			printBB(parallelId, n->bb);
			if (n->leaf) {
				for (std::vector<Body>::iterator it = n->bodies.begin(); it != n->bodies.end(); it++) {
					if (!it->refinement) {
						printBody(this->parallelId, *it);
					}
				}
			}
		}
	}
}
