#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <iostream>
#include <QFile>
#include <QMessageBox>
#include <QFileDialog>
#include <QJsonObject>

using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Character* c = new Character();
    currentCharacter = c;
    characters.append(c);
    ui->ageLineEdit->setValidator(new QIntValidator(0, 999999, ui->ageLineEdit));
    ui->niveauLineEdit->setValidator(new QIntValidator(0, 999999, ui->niveauLineEdit));
    ui->tailleLineEdit->setValidator(new QDoubleValidator(0.0, 999999.0, 1,ui->tailleLineEdit));
    loadImage(QString("data/images/logo.png"));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete currentCharacter;

    for(Character* c : characters) {
        delete c;
    }
}



void MainWindow::loadNewCharacter(){
    QString fileName = QFileDialog::getOpenFileName(this, "Open the file");
    if(fileName.isEmpty()) return;
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Fichier non valide" + file.errorString());
        return;
    }

    file.close();

    Character* c = new Character(&file);
    currentCharacter = c;
    characters.append(c);
    createNewCharacter(c);
    currentFile = fileName;
}

void MainWindow::createNewCharacter(Character* p) {
    currentCharacter = p;
    characters.append(p);

    ui->nomLineEdit->setText(p->getNom());
    ui->ageLineEdit->setText(QString::number(p->getAge()));
    ui->raceLineEdit->setText(p->getRace());
    ui->classeLineEdit->setText(p->getClasse());
    ui->niveauLineEdit->setText(QString::number(p->getNiveau()));
    ui->sexeLineEdit->setText(p->getSexe());
    ui->tailleLineEdit->setText(QString::number(p->getTaille()));

    ui->charismeSpinBox->setValue(p->getSkills()[0]);
    ui->dexteriteSpinBox->setValue(p->getSkills()[1]);
    ui->enduranceSpinBox->setValue(p->getSkills()[2]);
    ui->forceSpinBox->setValue(p->getSkills()[3]);
    ui->intelligenceSpinBox->setValue(p->getSkills()[4]);
    ui->sagesseSpinBox->setValue(p->getSkills()[5]);

    ui->modCharismeSpinBox->setValue(p->getSkillsMod()[0]);
    ui->modDexteriteSpinBox->setValue(p->getSkillsMod()[1]);
    ui->modEnduranceSpinBox->setValue(p->getSkillsMod()[2]);
    ui->modForceSpinBox->setValue(p->getSkillsMod()[3]);
    ui->modIntelligenceSpinBox->setValue(p->getSkillsMod()[4]);
    ui->modSagesseSpinBox->setValue(p->getSkillsMod()[5]);

    for (int i = 0; i < p->getStats().size(); ++i) {
        QString spinBoxName = QString("spinBox%1").arg(i+1);
        QSpinBox* spinBox = this->findChild<QSpinBox*>(spinBoxName);
        if (spinBox) {
            spinBox->setValue(p->getStats()[i]);
        }
    }
    loadImage(p->getImage());
}


void MainWindow::loadImage(QString fileName) {
    QString ext[] = {"png", "jpeg", "jpg"};
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Cannot open image: " +
                                                  file.errorString());
    }else{
        QString text = file.fileName();
        bool acceptedExt = false;
        for(QString e : ext) {
            if(text.endsWith(e)) acceptedExt = true;
        }
        if(!acceptedExt) {
            QMessageBox::warning(this, "Warning", "Format de fichier incorrect");
            return;
        }
        ui->imageLabel->setText(text);
        QPixmap px(fileName);
        ui->imageLabel->setPixmap(px);
        file.close();
    }
}

void MainWindow::exportJson(){
    QString fileName;
    if (currentFile.isEmpty()) {
        fileName = QFileDialog::getSaveFileName(this, "Save");
        currentFile = fileName;
    } else {
        fileName = currentFile;
    }
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
        return;
    }
    setWindowTitle(fileName);

    if(edition){
        //appelle a funct qui prend val ui pour mettre dans c
    }
    //Prend de c pour mettre dans json
    QJsonObject json;
    /*
    json["name"] = ui->titleEdit->text();
    json["city"] =ui->locEdit->text();
    json["departement"] = ui->depSpin->text();
    json["difficulty"] = ui->diffSpin->value();
    json["duration"] = ui->durationSpin->value();
    json["length"] = ui->lengthSpin->value();
    json["image"] = ui->imagePath->text();

    QJsonArray steps;
    int cpt=0;
    for(Step step: currentPath->getStep()){
        cpt++;
        QJsonObject stepObject;
        stepObject["numero"] = cpt;
        stepObject["title"] = step.getTitle();
        stepObject["GPS"] = step.toGPSFormat();
        stepObject["reponse"] = step.getResponse();
        QJsonArray dialogues;
        for(int i=0; i<step.getTexte().size(); i++){
            QJsonObject dialogueObject;
            dialogueObject["personnage"] = step.getPersonnage()[i];
            dialogueObject["texte"] = step.getTexte()[i];
            dialogues.append(dialogueObject);
        }
        stepObject["dialogue"] = dialogues;
        steps.append(stepObject);
    }
    json["steps"] = steps;
    QJsonDocument doc(json);
    file.write(doc.toJson());
    */
    file.close();
}

void MainWindow::exportJsonAs(){
    QString fileName = QFileDialog::getSaveFileName(this, "Save as");
    QFile file(fileName);

    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
        return;
    }
    setWindowTitle(fileName);
    currentFile = fileName;

    if(edition){
        //appelle a funct qui prend val ui pour mettre dans c
    }
    //Prend de c pour mettre dans json
    QJsonObject json;
    /*
    json["name"] = ui->titleEdit->text();
    json["city"] =ui->locEdit->text();
    json["departement"] = ui->depSpin->text();
    json["difficulty"] = ui->diffSpin->value();
    json["duration"] = ui->durationSpin->value();
    json["length"] = ui->lengthSpin->value();
    json["image"] = ui->imagePath->text();

    QJsonArray steps;
    int cpt=0;
    for(Step step: currentPath->getStep()){
        cpt++;
        QJsonObject stepObject;
        stepObject["numero"] = cpt;
        stepObject["title"] = step.getTitle();
        stepObject["GPS"] = step.toGPSFormat();
        stepObject["reponse"] = step.getResponse();
        QJsonArray dialogues;
        for(int i=0; i<step.getTexte().size(); i++){
            QJsonObject dialogueObject;
            dialogueObject["personnage"] = step.getPersonnage()[i];
            dialogueObject["texte"] = step.getTexte()[i];
            dialogues.append(dialogueObject);
        }
        stepObject["dialogue"] = dialogues;
        steps.append(stepObject);
    }
    json["steps"] = steps;
    QJsonDocument doc(json);
    file.write(doc.toJson());
    */
    file.close();
}

void MainWindow::on_actionEditer_triggered(){
    if(edition){
        //Mode edition
    }else{
        //Mode visualisation
    }
    edition=!edition;
}


void MainWindow::on_actionBlocNote_triggered(){
    if(notePad){
        //Menu notepad ouvert
    }else{
        //Menu notepad fermé
    }
    notePad=!notePad;
}


void MainWindow::on_actionOuvrir_une_fiche_triggered(){this->loadNewCharacter();}
void MainWindow::on_actionNouvelle_fiche_triggered(){this->createNewCharacter(new Character());}
void MainWindow::on_actionSauvegarder_triggered(){this->exportJson();}
void MainWindow::on_actionEnregistrer_sous_triggered(){this->exportJsonAs();}
void MainWindow::on_actionFermer_triggered(){QApplication::quit();}

