/*
 * Copyright (c) 2015, University of Kaiserslautern
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors:
 *    Janik Schlemminger
 *    Robert Gernhardt
 *    Matthias Jung
 */

#include "traceanalyzer.h"
#include "ui_traceanalyzer.h"
#include "tracefiletab.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QDateTime>
#include "QMessageBox"
#include <iostream>

void TraceAnalyzer::setUpStatusBar()
{
    statusLabel = new QLabel(this);
    statusBar()->addWidget(statusLabel);
}

void TraceAnalyzer::setUpGui()
{
    ui->setupUi(this);
    setUpStatusBar();
    ui->traceFileTabs->clear();
}


TraceAnalyzer::TraceAnalyzer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TraceAnalyzer)
{
    setUpGui();
    // Disable actions except for "Open" until some file is open.
    ui->actionReload_all->setEnabled(false);
    ui->actionSaveChangesToDB->setEnabled(false);
    ui->actionClose_all->setEnabled(false);
    ui->actionTest->setEnabled(false);
    ui->actionMetrics->setEnabled(false);
}

TraceAnalyzer::TraceAnalyzer(QSet<QString> paths, StartupOption option,
                             QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::TraceAnalyzer)
{
    setUpGui();

    for (const QString &path : paths)
        openTracefile(path);

    if (option == StartupOption::runTests) {
        ui->actionTest->trigger();
    }
}

TraceAnalyzer::~TraceAnalyzer()
{
    delete ui;
}

void TraceAnalyzer::on_actionOpen_triggered()
{
    QStringList paths = QFileDialog::getOpenFileNames(this,
                                                      tr("Open Tracefile"),
                                                      "../simulator/",
                                                      tr("Tracefile (*.tdb)"));
    if (paths.isEmpty()) {
        return;
    }

    for (const QString &path : paths) {
        openTracefile(path);
    }
}

void TraceAnalyzer::openTracefile(const QString &path)
{
    if (openedTraceFiles.contains(path))
        return;

    TraceFileTab *tab = new TraceFileTab(this, path);
    connect(tab, SIGNAL(statusChanged(QString, bool)), this,
            SLOT(statusChanged(QString, bool)));
    ui->traceFileTabs->addTab(tab, QFileInfo(path).baseName());
    openedTraceFiles.insert(path);

    // Enable actions
    ui->actionReload_all->setEnabled(true);
    ui->actionSaveChangesToDB->setEnabled(true);
    ui->actionClose_all->setEnabled(true);
    ui->actionTest->setEnabled(true);
    ui->actionMetrics->setEnabled(true);

    statusLabel->clear();
}

void TraceAnalyzer::on_traceFileTabs_tabCloseRequested(int index)
{
    TraceFileTab *traceFileTab = static_cast<TraceFileTab *>
                                 (ui->traceFileTabs->widget(index));
    openedTraceFiles.remove(traceFileTab->getPathToTraceFile());
    ui->traceFileTabs->removeTab(index);
    delete traceFileTab;
}

void TraceAnalyzer::on_actionClose_all_triggered()
{
    while (ui->traceFileTabs->count())
        on_traceFileTabs_tabCloseRequested(0);

    // All files closed. Disable actions except for "Open".
    ui->actionReload_all->setEnabled(false);
    ui->actionSaveChangesToDB->setEnabled(false);
    ui->actionClose_all->setEnabled(false);
    ui->actionTest->setEnabled(false);
    ui->actionMetrics->setEnabled(false);

    statusLabel->clear();
}

void TraceAnalyzer::on_actionReload_all_triggered()
{
    TraceFileTab *traceFileTab;

    // Remove all tabs
    int tabIndex = 0;
    while (ui->traceFileTabs->count() != 0) {
        traceFileTab = static_cast<TraceFileTab *>(ui->traceFileTabs->widget(0));
        std::cout << "Closing tab #" << tabIndex << " \"" <<
                  traceFileTab->getPathToTraceFile().toStdString() << "\"" << std::endl;

        ui->traceFileTabs->removeTab(0);
        delete traceFileTab;

        tabIndex++;
    }

    QList<QString> list = openedTraceFiles.toList();
    qSort(list);

    // Recreate all tabs
    tabIndex = 0;
    for (auto path : list) {
        std::cout << "Reopening tab# " << tabIndex << " \"" << path.toStdString() <<
                  "\"" << std::endl;

        traceFileTab = new TraceFileTab(this, path);
        connect(traceFileTab, SIGNAL(statusChanged(QString, bool)), this,
                SLOT(statusChanged(QString, bool)));
        ui->traceFileTabs->addTab(traceFileTab, QFileInfo(path).baseName());

        tabIndex++;
    }

    this->statusChanged(QString("All databases reloaded "), true);
}

void TraceAnalyzer::on_actionSaveChangesToDB_triggered()
{
    for (int index = 0; index < ui->traceFileTabs->count(); index++) {
        // Changes in the database files will trigger the file watchers from
        // the TraceFileTab class. They generate signals connected to TraceAnalyzer::statusChanged().
        TraceFileTab *traceFileTab = static_cast<TraceFileTab *>
                                     (ui->traceFileTabs->widget(index));
        traceFileTab->commitChangesToDB();
    }
}

void TraceAnalyzer::statusChanged(QString message, bool saveChangesEnable)
{
    statusLabel->setText(message + QTime::currentTime().toString());
    ui->actionSaveChangesToDB->setEnabled(saveChangesEnable);
}

void TraceAnalyzer::on_actionTest_triggered()
{
    evaluationTool.raise();
    evaluationTool.activateWindow();
    evaluationTool.showAndRunTests(openedTraceFiles.toList());
}

void TraceAnalyzer::on_actionMetrics_triggered()
{
    evaluationTool.raise();
    evaluationTool.activateWindow();
    evaluationTool.showAndEvaluateMetrics(openedTraceFiles.toList());
}
