/**
 * \file gui/edit/edit_settings/editsettings.cpp
 * \date 23/2/2019
 * \author Olivier Langella
 * \brief dialog box to edit global settings
 */

/*******************************************************************************
 * Copyright (c) 2019 Olivier Langella <olivier.langella@u-psud.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/>.
 *
 * Contributors:
 *     Olivier Langella <olivier.langella@u-psud.fr> - initial API and
 *implementation
 ******************************************************************************/

#include "editsettings.h"
#include <QDebug>
#include <QSettings>

#include "ui_edit_settings.h"
#include <QFileDialog>
#include <QProcess>
#include <pappsomspp/core/exception/exceptionnotfound.h>
#include <QMessageBox>
#include "gui/mainwindow.h"

EditSettings::EditSettings(MainWindow *parent)
  : QDialog(parent), ui(new Ui::EditSettingsDialog)
{
  ui->setupUi(this);
  mp_mainWindow = parent;

  QSettings settings;
  QString xic_extraction_method =
    settings.value("global/xic_extractor", "pwiz").toString();
  ui->xic_reader_buffered_button->setChecked(true);
  if(xic_extraction_method == "pwiz")
    {
      ui->xic_reader_buffered_button->setChecked(false);
    }

  QString tandemwrapper_path =
    settings.value("timstof/tandemwrapper_path", "").toString();
  QString tmp_dir_path = settings.value("timstof/tmp_dir_path", "").toString();
  QString spectrum_load_method =
    settings.value("timstof/spectrum_load_method", "mgf").toString();

  // ui->tandemwrapper_path_line->setText(tandemwrapper_path);
  ui->tmp_dir_line->setText(tmp_dir_path);
  ui->tdf_button->setChecked(true);
  if(spectrum_load_method == "mgf")
    {
      ui->mgf_button->setChecked(true);
    }
  connect(this,
          &EditSettings::operateFreeAllMsRunReaders,
          mp_mainWindow,
          &MainWindow::doFreeAllMsRunReaders);
}


EditSettings::~EditSettings()
{
  qDebug();

  delete ui;
  qDebug();
}


void
EditSettings::done(int r)
{
  if(QDialog::Accepted == r) // ok was pressed
    {
      QSettings settings;
      QString xic_extraction_method = "pwiz";
      if(ui->xic_reader_buffered_button->isChecked())
        {
          xic_extraction_method = "buffered";
        }
      settings.setValue("global/xic_extractor", xic_extraction_method);


      QString r_path   = ui->r_path_line->text();
      QFileInfo r_file = QFileInfo(r_path);
      if(r_file.exists() && r_file.isExecutable())
        {
          settings.setValue("path/r_binary", r_file.absoluteFilePath());
        }
      else
        {
          ui->r_path_line->clear();
          /*
         QMessageBox::warning(this, tr("R installation Error"),
                              tr("The R.exe path given isn't "
                                 "working\n Please check file path!!"));
                                 */
        }

      QString rscript_path   = ui->rscript_path_line->text();
      QFileInfo rscript_file = QFileInfo(rscript_path);
      if(rscript_file.exists() && rscript_file.isExecutable())
        {
          settings.setValue("path/rscript_binary",
                            rscript_file.absoluteFilePath());
        }
      else
        {
          ui->rscript_path_line->clear();
          /*
         QMessageBox::warning(this, tr("R installation Error"),
                              tr("The R.exe path given isn't "
                                 "working\n Please check file path!!"));
                                 */
        }


      QString tmp_dir_path = ui->tmp_dir_line->text();
      if(QFileInfo(tmp_dir_path).isDir())
        {
          settings.setValue("timstof/tmp_dir_path", tmp_dir_path);
        }

      QString spectrum_load_method = "mgf";
      if(ui->tdf_button->isChecked())
        {
          spectrum_load_method = "tdf";
        }
      settings.setValue("timstof/spectrum_load_method", spectrum_load_method);
      emit operateFreeAllMsRunReaders();

      QDialog::done(r);
      return;
    }
  else // cancel, close or exc was pressed
    {
      QDialog::done(r);
      return;
    }
}

void
EditSettings::selectRbinaryPath()
{
  QFileDialog dlg(this, tr("Select R.exe"));
  dlg.setOption(QFileDialog::DontUseNativeDialog, true);
  dlg.setFilter(QDir::Executable | QDir::Files);

  QString existing_filepath = ui->r_path_line->text();
  QString file =
    dlg.getOpenFileName(this, tr("Select R.exe"), existing_filepath);

  if(!file.isEmpty() && !file.isNull())
    {
      ui->r_path_line->setText(file);
    }
}

void
EditSettings::selectRscriptPath()
{
  QFileDialog dlg(this, tr("Select Rscript.exe"));
  dlg.setOption(QFileDialog::DontUseNativeDialog, true);
  dlg.setFilter(QDir::Executable | QDir::Files);

  QString existing_filepath = ui->rscript_path_line->text();
  QString file =
    dlg.getOpenFileName(this, tr("Select Rscript.exe"), existing_filepath);

  if(!file.isEmpty() && !file.isNull())
    {
      ui->rscript_path_line->setText(file);
    }
}


void
EditSettings::selectTmpDirPath()
{
  QString selected_dir = ui->tmp_dir_line->text();

  QString dir = QFileDialog::getExistingDirectory(
    this,
    tr("Open Directory"),
    selected_dir,
    QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

  if(!dir.isEmpty() && !dir.isNull())
    {
      ui->tmp_dir_line->setText(dir);
    }
}

bool
EditSettings::testTandemWrapperWorks(QString tandemwrapper_path)
{
  QProcess *my_process = new QProcess();
  QStringList argument;
  argument << "-v";
  my_process->start(tandemwrapper_path, argument);

  qDebug();
  if(!my_process->waitForStarted())
    {
      QString err =
        QObject::tr(
          "Could not start tandemwrapper process '%1' with arguments '%2': %3")
          .arg(tandemwrapper_path)
          .arg(argument.join(QStringLiteral(" ")))
          .arg(my_process->errorString());
      throw pappso::PappsoException(err);
    }

  while(my_process->waitForReadyRead(1000))
    {
    }
  QByteArray result = my_process->readAllStandardOutput();
  QRegularExpression parse_version("tandemwrapper \\d*.\\d*.\\d*\\n");
  if(parse_version.match(result.constData()).hasMatch())
    {
      qDebug() << result.constData();
      return true;
    }
  qDebug();
  return false;
}
