#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QStandardPaths>

#include "recordmanager.h"

const QString RecordManager::record_dir =
    QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/comp2012h_pipes";
const QString RecordManager::record_path =
    QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/comp2012h_pipes/record.txt";

RecordManager::RecordManager()
{
    create_file();
    load_file();
}

void RecordManager::create_file()
{
    // Check if the record file exists. If no, create it.
    QDir dir(record_dir);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    QFileInfo check_file(record_path);
    if (!check_file.exists() || !check_file.isFile()) {
        QFile new_file(record_path);
        new_file.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text);
        QTextStream out(&new_file);
        for (int i = 1; i <= NUM_OF_LEVELS; i++) {
            out << -1 << endl;
        }
        new_file.close();
    }
}

void RecordManager::load_file()
{
    QFile record_file(record_path);
    record_file.open(QIODevice::ReadOnly | QIODevice::Text);
    QString s;
    for (int i = 1; i <= NUM_OF_LEVELS; i++) {
        s = record_file.readLine();
        records[i] = s.toInt();
    }
    record_file.close();
}

int RecordManager::get_record(int level)
{
    return records[level];
}

int RecordManager::get_num_of_levels()
{
    return NUM_OF_LEVELS;
}

void RecordManager::update_record(int level, int value)
{
    if (records[level] == -1 || value < records[level])
        {
            records[level] = value;
            QFile record_file(record_path);
            record_file.open(QIODevice::ReadWrite | QIODevice::Truncate);
            QTextStream out(&record_file);
            for (int i = 1; i <= NUM_OF_LEVELS; i++) {
                out << records[i] << endl;
            }
            record_file.close();
        }
}
