/***************************************************************************
 *   Copyright (C) 2005-2008 by Eugene V. Lyubimkin aka jackyf             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License                  *
 *   (version 3 or above) as published by the Free Software Foundation.    *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU GPL                        *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA               *
 ***************************************************************************/
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QStringList>
#include <QTime>
#include <QtDebug>

#include "UserProfile.hpp"
#include "Setup.hpp"

const QString delimiter = "|";

QString ExerciseResult::toString() const
{
	QString result;
	result += QString::number(timestamp);
	result += delimiter + QString::number(symbolCount);
	result += delimiter + QString::number(millisecsSpent);
	result += delimiter + worseTriLetter;
	result += delimiter + QString::number(rhythmPercent);
	for (int i = 0; i < mistakes.size(); ++i)
	{
		result += delimiter;
		result += mistakes[i];
	}

	return result;
}

ExerciseResult ExerciseResult::fromString(const QString& dump)
{
	QStringList strings = dump.split(delimiter);

	ExerciseResult result;
	int z = 0;
	result.timestamp = strings.at(z++).toULong();
	result.symbolCount = strings.at(z++).toULong();
	result.millisecsSpent = strings.at(z++).toULong();
	result.worseTriLetter = strings.at(z++);
	result.rhythmPercent = strings.at(z++).toULong();
	for (int i = z; i < strings.size(); ++i)
	{
		result.mistakes.push_back(strings.at(i));
	}

	return result;
}

UserProfile::UserProfile(const QString& profilePath)
	: path(profilePath)
{
	QFile fin(profilePath);
	if (!fin.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		qFatal("Cannot load the profile %s", qPrintable(path));
	}
	QTextStream in(&fin);
	in.setCodec("UTF-8");

	this->layoutString = in.readLine();
	this->layout.read(pathToLayouts + this->layoutString);

	QString tmp;
	while (!(in.atEnd()))
	{
		tmp = in.readLine();
		if (!(tmp.isEmpty()))
		{
			this->exerciseResults.push_back(ExerciseResult::fromString(tmp));
		}
	}
	fin.close();
}

void UserProfile::exerciseDone(const ExerciseResult& exerciseResult)
{
	exerciseResults.push_back(exerciseResult);
	QFile fout(path);
	if (!fout.open(QIODevice::Append | QIODevice::Text))
	{
		qFatal("Cannot renew the profile %s", qPrintable(path));
	}
	QTextStream out(&fout);
	out.setCodec("UTF-8");
	out << exerciseResult.toString() << endl;
	fout.close();
}

const vector<ExerciseResult>& UserProfile::exercises() const
{
	return exerciseResults;
}

QString UserProfile::getFortuneArgumentsLine() const
{
	return layout.getLayoutFortuneParam();
}

QString UserProfile::getLayoutString() const
{
	return layoutString;
}

const Layout& UserProfile::getLayout() const
{
	return layout;
}

size_t UserProfile::getTotalSecondCount() const
{
	size_t result = 0;
	for (size_t i = 0; i < exerciseResults.size(); ++i)
	{
		result += exerciseResults[i].millisecsSpent;
	}
	return result / 1000;
}

size_t UserProfile::getTotalMistakeCount() const
{
	size_t result = 0;
	for (size_t i = 0; i < exerciseResults.size(); ++i)
	{
		result += exerciseResults[i].mistakes.size();
	}
	return result / 2; // mistakes are stored by pairs
}

size_t UserProfile::getTotalSymbolCount() const
{
	size_t result = 0;
	for (size_t i = 0; i < exerciseResults.size(); ++i)
	{
		result += exerciseResults[i].symbolCount;
	}
	return result;
}


QString UserProfile::getGeneralStats() const
{
	size_t exerciseCount = this->exercises().size();

	float averageMistakes =
		exerciseCount ? static_cast<float>(this->getTotalMistakeCount()) / exerciseCount : 0;

	size_t secondCount = this->getTotalSecondCount();
	QTime time(0, 0);
	time = time.addSecs(secondCount);
	QString timeString = time.toString(QString("hh:mm:ss"));

	if (size_t days = secondCount/24/60/60)
	{
		timeString.prepend(QString("%1d ").arg(days));
	}

	float averageTypingSpeed =
		secondCount ? static_cast<float>(this->getTotalSymbolCount() * 60 / secondCount) : 0;

	QString generalTip =
		QCoreApplication::translate("UserProfile", "%7"
			"Keyboard layout: %1"
			"Exercises done: %2"
			"Symbols typed: %3"
			"Time spent: %4"
			"Average mistake count by exercise: %5"
			"Average typing speed: %6"
		)
		.arg(
		"<b>%1</b><br>",
		"<b>%2</b><br>",
		"<b>%3</b><br>",
		"<b>%4</b><br>",
		"<b>%L5</b><br>",
		"<b>%6</b></div>",
		"<div align=center><font color='blue'>%7</font></div><br><div align=left>")

		.arg(this->getLayoutString())
		.arg(exerciseCount)
		.arg(this->getTotalSymbolCount())
		.arg(timeString)
		.arg(averageMistakes, 0, 'f', 2)
		.arg(averageTypingSpeed)
		.arg(path.mid(path.lastIndexOf(QChar('/')) + 1));

	return generalTip;
}

enum UserProfile::ConstructNewProfileResult UserProfile::constructNewProfile(const QString& newProfileName, const QString& layout)
{
	qDebug() << "Constructing new profile" << newProfileName << "with layout" << layout;
	QFile profileFile(pathToUserProfiles + newProfileName);
	QFile defaultCombinationFile(pathToDefaultProfiles + layout);
	if (!defaultCombinationFile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		return CombinationError;
	}
	else if (profileFile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		return ProfileExists;
	}
	else
	{
		profileFile.open(QIODevice::WriteOnly | QIODevice::Text);
		QTextStream combinationFileStream(&defaultCombinationFile);
		QTextStream profileFileStream(&profileFile);
		QString defaultCombination = combinationFileStream.readLine();
		profileFileStream << layout << endl;
		profileFileStream << QString::number(time(NULL)) << delimiter
			<< "0" << delimiter << "0" << delimiter
			<< defaultCombination << delimiter << "0" << endl;

		return Ok;
	}
}

QString UserProfile::getPath() const
{
	return path;
}

bool UserProfile::isCorrectProfile(const QString& profilePath)
{
	QFile fin(profilePath);
	if (!fin.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		qCritical("Failed to read the existing file %s", qPrintable(profilePath));
		return false;
	}
	QTextStream in(&fin);

	QString layoutString = in.readLine();
	if (QFile::exists(pathToLayouts + layoutString))
	{
		return true;
	}
	else
	{
		qCritical("Layout %s doesn't exist.", qPrintable(layoutString));
		return false;
	}
}

