#include "WordsPeak.h"
#include <QDebug>

using namespace Lex;

ExStream::ExStream() :file_target(nullptr), text_input(nullptr),
current_line(""), current_row(-1), current_col(0) {}

ExStream::~ExStream() {
	if (file_target)
		delete file_target;
	if (text_input)
		delete text_input;
}

int ExStream::initSource(const QString & path)
{
	if (file_target)
		delete file_target;
	if (text_input)
		delete text_input;

	if (!QFile(path).exists())
		return -1;

	file_target = new QFile(path);
	if (!file_target->open(QIODevice::ReadOnly | QIODevice::Text))
		return -2;

	text_input = new QTextStream(file_target);
	return 0;
}

std::tuple<ExStream::n_row, ExStream::n_col, QChar> ExStream::read()
{
	if (current_col >= current_line.length()) {
		if (!text_input->atEnd()) {
			current_row++;
			current_col = 0;
			current_line = text_input->readLine() + '\n';
		}
		else {
			return std::make_tuple(-1, -1, EOF);
		}
	}

	return  std::make_tuple(current_row, current_col, current_line[current_col++]);
}

