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

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

using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    notePad = new NotePad();
    connect(notePad, &NotePad::demandeSauvegarde, this, &MainWindow::recevoirSauvegarde);
    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 notePad;
    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) {
    notePad->setTexte(p->getTexteBlocNote());
    currentCharacter = p;
    characters.append(p);
    setUi(p);
}


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::saveJson(){
    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;
    }

    if(edition){
        getUi();
    }
    notePad->getUi();
    currentCharacter->setTexteBlocNote(notePad->getTexte());
    QJsonObject json;
    json["name"] = currentCharacter->getNom();
    json["age"] = currentCharacter->getAge();
    json["race"] = currentCharacter->getRace();
    json["classe"] = currentCharacter->getClasse();
    json["niveau"] = currentCharacter->getNiveau();
    json["sexe"] = currentCharacter->getSexe();
    json["taille"] = currentCharacter->getTaille();
    json["vie"] = currentCharacter->getVie();
    json["image"] = currentCharacter->getImage();
    json["blocNote"] = currentCharacter->getTexteBlocNote();
    json["backPack"] = currentCharacter->getTexteBackPack();

    QJsonArray skillsArray;
    for(int i=0; i<currentCharacter->getSkills().size(); i++){
        skillsArray.append(QJsonValue(currentCharacter->getSkills()[i]));
    }
    json["skills"] = skillsArray;
    QJsonArray skillsModArray;
    for(int i=0; i<currentCharacter->getSkillsMod().size(); i++){
        skillsModArray.append(QJsonValue(currentCharacter->getSkillsMod()[i]));
    }
    json["skillsMod"] = skillsModArray;
    QJsonArray statsArray;
    for(int i=0; i<currentCharacter->getStats().size(); i++){
        statsArray.append(QJsonValue(currentCharacter->getStats()[i]));
    }
    json["stats"] = statsArray;

    QJsonDocument doc(json);
    file.write(doc.toJson());
    file.close();
}

void MainWindow::saveAsJson(){
    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){
        getUi();
    }
    notePad->getUi();
    currentCharacter->setTexteBlocNote(notePad->getTexte());
    QJsonObject json;
    json["name"] = currentCharacter->getNom();
    json["age"] = currentCharacter->getAge();
    json["race"] = currentCharacter->getRace();
    json["classe"] = currentCharacter->getClasse();
    json["niveau"] = currentCharacter->getNiveau();
    json["sexe"] = currentCharacter->getSexe();
    json["taille"] = currentCharacter->getTaille();
    json["vie"] = currentCharacter->getVie();
    json["image"] = currentCharacter->getImage();
    json["blocNote"] = currentCharacter->getTexteBlocNote();
    json["backPack"] = currentCharacter->getTexteBackPack();

    QJsonArray skillsArray;
    for(int i=0; i<currentCharacter->getSkills().size(); i++){
        skillsArray.append(QJsonValue(currentCharacter->getSkills()[i]));
    }
    json["skills"] = skillsArray;
    QJsonArray skillsModArray;
    for(int i=0; i<currentCharacter->getSkillsMod().size(); i++){
        skillsModArray.append(QJsonValue(currentCharacter->getSkillsMod()[i]));
    }
    json["skillsMod"] = skillsModArray;
    QJsonArray statsArray;
    for(int i=0; i<currentCharacter->getStats().size(); i++){
        statsArray.append(QJsonValue(currentCharacter->getStats()[i]));
    }
    json["stats"] = statsArray;

    QJsonDocument doc(json);
    file.write(doc.toJson());
    file.close();
}


void MainWindow::getUi(){
    currentCharacter->setNom(ui->nomLineEdit->text());
    currentCharacter->setAge(ui->ageLineEdit->text().toInt());
    currentCharacter->setRace(ui->raceLineEdit->text());
    currentCharacter->setClasse(ui->classeLineEdit->text());
    currentCharacter->setNiveau(ui->niveauLineEdit->text().toInt());
    currentCharacter->setSexe(ui->sexeLineEdit->text());
    currentCharacter->setTaille(ui->tailleLineEdit->text().toFloat());

    QList<int> skills;
    skills.append(ui->charismeSpinBox->value());
    skills.append(ui->dexteriteSpinBox->value());
    skills.append(ui->enduranceSpinBox->value());
    skills.append(ui->forceSpinBox->value());
    skills.append(ui->intelligenceSpinBox->value());
    skills.append(ui->sagesseSpinBox->value());
    skills.append(ui->pvSpinBox->value());
    currentCharacter->setSkills(skills);
    QList<int> skillsMod;
    skillsMod.append(ui->modCharismeSpinBox->value());
    skillsMod.append(ui->modDexteriteSpinBox->value());
    skillsMod.append(ui->modEnduranceSpinBox->value());
    skillsMod.append(ui->modForceSpinBox->value());
    skillsMod.append(ui->modIntelligenceSpinBox->value());
    skillsMod.append(ui->modSagesseSpinBox->value());
    currentCharacter->setSkills(skillsMod);
    QList<int> stats;
    for (int i = 0; i < currentCharacter->getStats().size(); ++i) {
        QString spinBoxName = QString("spinBox%1").arg(i+1);
        QSpinBox* spinBox = this->findChild<QSpinBox*>(spinBoxName);
        if (spinBox) {
            stats.append(spinBox->value());
        }
    }
    currentCharacter->setStats(stats);
    //currentCharacter->setImage();
}




void MainWindow::setUi(Character* 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->pvSpinBox->setValue(p->getVie());

    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::on_actionEditer_triggered(){
    if(edition){
        //Mode edition
    }else{
        //Mode visualisation
    }
    edition=!edition;
}


void MainWindow::on_actionBlocNote_triggered(){
    this->notePad->show();
}


void MainWindow::recevoirSauvegarde(QString contenu){
    currentCharacter->setTexteBlocNote(contenu);
    saveJson();
}



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->saveJson();}
void MainWindow::on_actionEnregistrer_sous_triggered(){this->saveAsJson();}
void MainWindow::on_actionFermer_triggered(){QApplication::quit();}

