/**
 * \file /gui/run/rworkflowrunviewbase.cpp
 * \date 3/11/2023
 * \author Olivier Langella
 * \brief base window for R run views
 */

/*******************************************************************************
 * Copyright (c) 2023 Olivier Langella
 *<Olivier.Langella@universite-paris-saclay.fr>.
 *
 * This file is part of i2MassChroQ.
 *
 *     i2MassChroQ is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     i2MassChroQ 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with i2MassChroQ.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#include "rworkflowrunviewbase.h"

#include <QCloseEvent>
#include <QMessageBox>
#include <QDir>
#include <QDebug>
#include <QSettings>
#include <QFileDialog>
#include <QDesktopServices>
#include "../mainwindow.h"
#include "../../input/mcqr/metadataodsreader.h"
#include <pappsomspp/core/exception/exceptionnotpossible.h>
#include <pappsomspp/core/exception/exceptionnotfound.h>

RworkflowRunViewBase::RworkflowRunViewBase(MainWindow *parent) : QWidget()
{
  mp_main = parent;


  qDebug();

  checkInstall();
}

RworkflowRunViewBase::~RworkflowRunViewBase()
{
}

void
RworkflowRunViewBase::checkInstall()
{
}


QString
RworkflowRunViewBase::toRboolean(bool is_ok) const
{
  if(is_ok)
    return "TRUE";
  return "FALSE";
}

void
RworkflowRunViewBase::closeEvent(QCloseEvent *event)
{

  qDebug() << "Close window";
  event->accept();
}


void
RworkflowRunViewBase::warning(const QString &message)
{
  QMessageBox::warning(this, tr("Error"), message);
}

bool
RworkflowRunViewBase::fileExists(const QString &filename) const
{
  QDir directory(m_workingDirectory);

  return (QFileInfo(directory.filePath(filename)).exists());
}

QString
RworkflowRunViewBase::filePath(const QString &filename) const
{
  QDir directory(m_workingDirectory);

  return (directory.filePath(filename));
}


bool
RworkflowRunViewBase::removeFile(const QString &filename) const
{
  QDir directory(m_workingDirectory);
  
  auto file =QFile(directory.filePath(filename));
  if (!file.exists()) return true;

  return (file.remove());
}

void
RworkflowRunViewBase::doSelectWorkingDirectory()
{

  QSettings settings;

  QString default_location = settings.value("path/mcqfile", "").toString();

  QString filename =
    QFileDialog::getExistingDirectory(this,
                                      tr("select %1 working directory").arg(m_rviewName),
                                      QDir(default_location).absolutePath());
  if(!filename.isEmpty())
    {

      getWidgetRprocess()->executeOnTheRecord(
        QString("setwd(\"%1\");\n").arg(filename));

      m_workingDirectory = filename;

      setWorkingDirectoryLabel();
    }
}


void
RworkflowRunViewBase::doGetRscript()
{

  QSettings settings;


  QString filename =
    QFileDialog::getSaveFileName(this,
                                 tr("Save R script run"),
                                 "~/untitled.R",
                                 tr("R Script (*.R);;All files (*.*)"));
  QFile qFile(filename);
  if(qFile.open(QIODevice::WriteOnly))
    {
      QTextStream out(&qFile);
      out << getWidgetRprocess()->getRscriptCode();
      qFile.close();
      launchDesktopSoftwareOnFile(filename);
    }
}

void
RworkflowRunViewBase::doGetRmdScript()
{

  QString title = "";
  if(mp_main->getProjectSp().get() != nullptr)
    {
      title = mp_main->getProjectSp().get()->getProjectName();
    }
  QSettings settings;


  QString filename =
    QFileDialog::getSaveFileName(this,
                                 tr("Save Rmd script"),
                                 "~/untitled.Rmd",
                                 tr("Rmd Script (*.Rmd);;All files (*.*)"));
  QFile qFile(filename);
  if(qFile.open(QIODevice::WriteOnly))
    {
      if(title.isEmpty())
        {
          title = QFileInfo(filename).baseName();
        }
      QTextStream out(&qFile);
      out << getWidgetRprocess()->getRmdScriptCode(title);
      qFile.close();
      launchDesktopSoftwareOnFile(filename);
    }
}

void
RworkflowRunViewBase::launchDesktopSoftwareOnFile(const QString &filePath) const
{
  QDesktopServices::openUrl(
    QUrl(QString("file:///").append(filePath), QUrl::TolerantMode));
}


McqrMetadataSet
RworkflowRunViewBase::readMetadata() const
{
  McqrMetadataSet metadata_set;
  try
    {
      QDir directory(m_workingDirectory);
      if(QFileInfo(directory.absoluteFilePath("metadata.ods")).exists())
        {
          QFile file(directory.absoluteFilePath("metadata.ods"));
          MetadataOdsReader handler;
          OdsDocReader reader(handler);
          reader.parse(file);

          metadata_set = handler.getMcqrMetadataSet();
        }
      else
        {
          throw pappso::ExceptionNotFound(
            QObject::tr("file %1 not found")
              .arg(directory.absoluteFilePath("metadata.ods")));
        }
    }
  catch(pappso::PappsoException &error)
    {
      throw pappso::PappsoException(
        QObject::tr("Cannot load metadata ods file: %1").arg(error.qwhat()));
    }
  qDebug();
  return metadata_set;
}
