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

namespace nbody {
	using namespace std;

	Tree::Tree() {
		//insert dummy root node
		this->nodes = new TreeNode(this);
	}

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

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

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

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

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

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

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

	vector<Body> Tree::dubinskiParse(string filename) {
		vector<Body> result;
		string line;
		ifstream infile(filename.c_str(), ifstream::in);
		double mass, px, py, pz, vx, vy, vz;

		while (infile >> mass >> px >> py >> pz >> vx >> vy >> vz) {
			Body b(px, py, pz, vx, vy, vz, mass);

			result.push_back(b);
		}
		infile.close();
		return result;
	}
}
