#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include "Node.hpp"
#include "Simulation.hpp"
#include "Tree.hpp"

namespace nbody {
	Tree::Tree(std::size_t parallelId_):
		nodes(createNode(this)), //insert dummy root node
		maxLeafBodies(16),
		parallelId(parallelId_),
		nodesView(this){}

	void Tree::clean() {
		//remove all nodes; refresh dummy first node
		nodesMemory.clear();
		nodes = createNode(this);
	}

	std::size_t Tree::numberOfNodes() const {
		return std::abs(std::distance(std::begin(nodesView), std::end(nodesView)));
	}

	bool Tree::isCorrect() const {
		return std::all_of(std::begin(nodesView), std::end(nodesView), [](const Node& n) { return n.isCorrect(); });
	}

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

		body.resetAcceleration();
		while (n != nodes) {
			if (n->sufficientForBody(body)) {
				body.accumulateForceOntoBody(n->representative);
				n = n->afterSubtree;
			} else if (n->leaf) {
				for (const auto& b : n->bodies) {
					body.accumulateForceOntoBody(b);
				}
				n = n->afterSubtree;
			} else {
				n = n->next;
			}
		}
	}

	//accumulate forces for whole tree (local particles)
	void Tree::computeForces() {
		for (auto& n : nodesView) {
			if (n.leaf) {
				for (auto& b : n.bodies) {
					if (!b.refinement) {
						accumulateForceOnto(b);
					}
				}
			}
		}
	}

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

		for (auto& node : nodesView) {
			if (node.leaf) {
				std::copy_if(std::begin(node.bodies), std::end(node.bodies), std::back_inserter(result), [](const Body& b) {return !b.refinement; });
			}
		}
		clean();
		return result;
	}

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

		if (!current->bb.isValid()) {
			//empty tree means no refinements
			return result;
		}
		while (current != 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(std::end(result), std::begin(current->bodies), std::end(current->bodies));
				current = current->next;
			} else {
				current = current->next;
			}
		}
		return result;
	}

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

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

	void Tree::rebuild() {
		build(extractLocalBodies());
	}

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

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

		for (auto& n : nodesView) {
			if (n.leaf) {
				for (auto& b : n.bodies) {
					if (!b.refinement) {
						b.integrate();
						bb.extend(b);
					}
				}
			}
		}
		return bb;
	}

	//determine local tree bounding box
	Box Tree::getLocalBB() const {
		Box result;
		for (const auto& n : nodesView) {
			if (n.leaf) {
				for (const auto& b : n.bodies) {
					if (!b.refinement) {
						result.extend(b);
					}
				}
			}
		}
		return result;
	}

	void Tree::print(std::size_t parallelId) const {
		for (const auto& n : nodesView) {
			n.bb.printBB(parallelId);
			if (n.leaf) {
				for (const auto& b : n.bodies) {
					if (!b.refinement) {
						b.print(this->parallelId);
					}
				}
			}
		}
	}
} // namespace nbody
