enum difficult{EASY, MEDIUM, HARD};
using  tab = QPair<difficult, QPair<QString,int>>;
std::multiset<tab, std::function<bool(tab,tab)>>* table;
HighScores::HighScores(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::HighScores)
{
    ui->setupUi(this);
    auto comp = [](tab a, tab b){ return a.first < b.first ? true : a.first == b.first ? a.second.second < b. second.second : false;};
    table = new std::multiset<tab, std::function<bool(tab,tab)>>(comp);
    std::string str, name;
    int time,di;
    file = new QFile("records.txt");
    if (file->exists()){
        file->open(QIODevice::ReadOnly);
        while(!file->atEnd()){
            str = file->readLine().toStdString();
            std::istringstream a(str);
            a >> name;
            a >> time;
            a >> di;
            table->insert(tab(static_cast<difficult>(di), QPair<QString,int>(QString(name.c_str()), time) ));
        }
        file->resize(0);
        file->close();
    }
}

HighScores::~HighScores()
{
    delete ui;
}

void HighScores::callAddIf(difficult diff){
    emit gettime();
    int h = 0;

    for(auto& i : *table)
        if(i.first==diff)
            h++;
    auto temp = *table->lower_bound(tab(diff,QPair<QString,int>("",0)));
    for(auto& i : *table)
        if(i.first == diff)
            temp = i;
    if(h < 10 || temp.second.second > time){
        QString name = QInputDialog::getText(this,"New Record", "Your name");
        if(name.size()>0)
            table->insert(tab(diff,QPair<QString,int>(name, time)));
        if(h == 10){
            
            table->erase(table->find(temp));
        }
    }
    file->open(QIODevice::WriteOnly);
    for(auto& i : *table)
        file->write(i.second.first.toUtf8()+ " " + QString::number(i.second.second).toUtf8() + " " + QString::number(i.first).toUtf8() + "\n");
    file->close();

}