/**
 * \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 XTPcpp.
 *
 *     XTPcpp 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.
 *
 *     XTPcpp 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 XTPcpp.  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/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() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;

  delete ui;
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}


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 tandemwrapper_path   = ui->tandemwrapper_path_line->text();
      QFileInfo tandemwrapper_file = QFileInfo(tandemwrapper_path);
      if(tandemwrapper_file.exists() && tandemwrapper_file.isExecutable())
        {
          if(testTandemWrapperWorks(tandemwrapper_path))
            {
              settings.setValue("timstof/tandemwrapper_path",
                                tandemwrapper_path);
            }
          else
            {
              QMessageBox::warning(this,
                                   tr("TandemWrapper Error"),
                                   tr("The TandemWrapper path given isn't "
                                      "working\n Please check file path!!"));
              return;
            }
        }
      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::selectTandemWrapperPath()
{
  QFileDialog dlg(this, tr("Select TandemWrapper"));
  dlg.setOption(QFileDialog::DontUseNativeDialog, true);
  dlg.setFilter(QDir::Executable | QDir::Files);

  QString existing_filepath = ui->tandemwrapper_path_line->text();
  QString file =
    dlg.getOpenFileName(this, tr("Select TandemWrapper"), existing_filepath);

  if(!file.isEmpty() && !file.isNull())
    {
      ui->tandemwrapper_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);


  if(!my_process->waitForStarted())
    {
      throw pappso::PappsoException(
        QObject::tr("X!Tandem %1 process failed to start"));
    }

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