/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK 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 Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

// Include .h file
#include "GeneratingCEPState.h"
#include "GeneratingCEPWidget.h"
#include "WizardMainWindow.h"
#include "DefaultGUIText.h"

#include <CepGenerator.h>
#include <ClassNameHandler.h>

// includes from coreschema
#include <Cep.hxx>
#include <Contact.hxx>

// inludes from Qt
#include <QDir>
#include <QRegularExpression>

// temporary include
#include <iostream>
#include <sstream>


static const QString cepSchemaNamespace = "http://camitk.imag.fr/cepcoreschema";

/**  Constructor */
GeneratingCEPState::GeneratingCEPState(QString name, GeneratingCEPWidget* widget, WizardMainWindow* mainWindow, cepcoreschema::Cep* domCep, QString* directoryName, QMap<QString, QStringList>* copyFilesMap)
    : WizardState(name, widget, mainWindow) {
    this->domCep = domCep;
    this->directoryName = directoryName;
    this->copyFilesMap = copyFilesMap;
}

void GeneratingCEPState::onEntry(QEvent* event) {
    WizardState::onEntry(event);
    QString cepName = domCep->name().c_str();
    std::cout << "cepName: " << cepName.toStdString() << std::endl;

    std::unique_ptr<cepcoreschema::Cep> domCepPtr(domCep);

    CepGenerator* cepGenerator = new CepGenerator(std::move(domCepPtr), (*directoryName));
    cepGenerator->process();
    delete cepGenerator;

    std::cout << "CEP generated !" << std::endl;

    std::cout << "Now, copying files" << std::endl;
    if (! copyFilesMap->isEmpty()) {
        std::cout << "CopyFilesMap not empty" << std::endl;
        QMap<QString, QStringList>::const_iterator it;
        for (it = copyFilesMap->constBegin(); it != copyFilesMap->constEnd(); ++it) {
            QString libraryName = it.key();
            QStringList totalFileNamesList = it.value();
            std::cout << "library Name: " << libraryName.toStdString() << std::endl;
            std::cout << "directory name: " << (*directoryName).toStdString() << std::endl;


            QFileInfo devDir(*directoryName);

            if (! devDir.isDir()) {
                QString msg = "Exception from Cep generation: \n The path " + (*directoryName) + " is not a directory\n";
                std::cout << msg.toStdString() << std::endl;
                throw (msg);
            }


            QDir dir;
            dir.cd(*directoryName);
            std::cout << "Now QDir is created !" << std::endl;


            //QString cepDirName = domCep.name().c_str();
            QString cepDirName = ClassNameHandler::getDirectoryName(cepName);
            libraryName = ClassNameHandler::getDirectoryName(libraryName);

            std::cout << "cpeDirName: " << cepDirName.toStdString() << ", libraryName: " << libraryName.toStdString() << std::endl;

            for (QString totalFileName : totalFileNamesList) {
                QFileInfo fileInfo(totalFileName);
                QString shortFileName = fileInfo.fileName();

                QString outputFileName = dir.absolutePath() + "/" + cepDirName + "/libraries/" + libraryName + "/" + shortFileName;

                std::cout << "outputFileName " << outputFileName.toStdString() << std::endl;
                QFile::copy(totalFileName, outputFileName);
            }

        }
    }

    auto* generatingCEPWidget = dynamic_cast<GeneratingCEPWidget*>(widget);
    if (generatingCEPWidget != nullptr) {
        QString cepDirectory = ClassNameHandler::getDirectoryName(cepName);

        QString text = defaultCEPSummary;
        text = text.replace(QRegularExpression("@WORKING_DIRECTORY@"), (*directoryName));
        text = text.replace(QRegularExpression("@CEP_DIRECTORY@"), cepDirectory);

        generatingCEPWidget->setTitle(text);
        generatingCEPWidget->setXmlTag("");
        /*
         QString newTitle = "Generating the following CEP in " + (*directoryName);
         generatingCEPWidget->setTitle(newTitle);

         QString xmlText;

         // Serialization of domCep to a std::string
         xml_schema::namespace_infomap map;
         map[""].name = cepSchemaNamespace.toStdString();
         map[""].schema = "Cep.xsd";
         std::ostringstream oss;
         cep(oss, *domCep, map);
         std::string stdString (oss.str ());
         xmlText = stdString.c_str();

         generatingCEPWidget->setXmlTag(xmlText);
         */
    }

}
