/*
 * 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 "tracenavigator.h"
#include "vector"

using namespace std;

TraceNavigator::TraceNavigator(QString path, QObject *parent)
    : QObject(parent), traceFile(path, true), changesToCommitExist(false)
{
    getCommentsFromDB();
}

TraceNavigator::~TraceNavigator()
{
}

/* Navigation
 *
 *
 */

void TraceNavigator::navigateToTime(traceTime time)
{
    if (time < 0)
        time = 0;
    else if (time > traceFile.getGeneralInfo().span.End())
        time = traceFile.getGeneralInfo().span.End();
    else {
        currentTraceTime = time;
        Q_EMIT currentTraceTimeChanged();
    }
}

void TraceNavigator::navigateToTransaction(ID id)
{
    navigateToTime(traceFile.getTransactionByID(id)->Span().Begin());
}


/* Comment and debug messages
 *
 */
void TraceNavigator::insertComment(const Comment &comment)
{
    comments.emplace(comment.Time(), comment);
    changesToCommitExist = true;
    Q_EMIT commentsChanged();
}

void TraceNavigator::removeCommentAtTime(traceTime time)
{
    auto found = comments.find(time);
    if (found != comments.end()) {
        comments.erase(found);
        changesToCommitExist = true;
        Q_EMIT commentsChanged();
    }
}



/* DB
 *
 */

void TraceNavigator::commitChangesToDB()
{
    vector<Comment> commentsToInsert;
    for (const auto &pair : comments) {
        commentsToInsert.push_back(pair.second);
    }

    traceFile.updateComments(commentsToInsert);
    changesToCommitExist = false;
}

void TraceNavigator::getCommentsFromDB()
{
    for (const Comment &comment : traceFile.getComments()) {
        comments.emplace(comment.Time(), comment);
    }
}

void TraceNavigator::refreshData()
{
    traceFile.refreshData();
    clearSelectedTransactions();
    navigateToTime(currentTraceTime);
}

/* Transaction Selection
 *
 *
 */

void TraceNavigator::addSelectedTransactions(const
                                             vector<shared_ptr<Transaction>> &transactions)
{
    for (const auto transaction : transactions) {
        selectedTransactions.push_back(transaction);
    }
    Q_EMIT selectedTransactionsChanged();
}

void TraceNavigator::addSelectedTransaction(const shared_ptr<Transaction>
                                            &transaction)
{
    selectedTransactions.push_back(transaction);
    Q_EMIT selectedTransactionsChanged();
}

void TraceNavigator::addSelectedTransaction(ID id)
{
    shared_ptr<Transaction> transaction = TraceFile().getTransactionByID(id);
    selectedTransactions.push_back(transaction);
    Q_EMIT selectedTransactionsChanged();
}

void TraceNavigator::selectTransaction(ID id)
{
    clearSelectedTransactions();
    addSelectedTransaction(id);
    navigateToTransaction(id);
}

void TraceNavigator::selectTransaction(const shared_ptr<Transaction>
                                       &transaction)
{
    selectTransaction(transaction->Id());
}

void TraceNavigator::selectNextTransaction()
{
    if (selectedTransactions.empty()
            || selectedTransactions.front()->Id() ==
            traceFile.getGeneralInfo().numberOfTransactions)
        selectFirstTransaction();
    else
        selectTransaction(selectedTransactions.front()->Id() + 1);
}

void TraceNavigator::selectPreviousTransaction()
{
    if (selectedTransactions.empty() || selectedTransactions.front()->Id() == 1)
        selectLastTransaction();
    else
        selectTransaction(selectedTransactions.front()->Id() - 1);
}

void TraceNavigator::selectFirstTransaction()
{
    selectTransaction(1);
}

void TraceNavigator::selectLastTransaction()
{
    selectTransaction(traceFile.getGeneralInfo().numberOfTransactions);
}


void TraceNavigator::selectNextRefresh()
{
    shared_ptr<Transaction> nextRefresh;

    if (!SelectedTransactions().empty())
        nextRefresh = traceFile.getNextRefresh(SelectedTransactions().front()->Id());
    else
        nextRefresh = traceFile.getNextRefresh(0);

    if (nextRefresh)
        selectTransaction(nextRefresh);
}

void TraceNavigator::selectNextActivate()
{
    shared_ptr<Transaction> nextActivate;

    if (!SelectedTransactions().empty())
        nextActivate = traceFile.getNextActivate(SelectedTransactions().front()->Id());
    else
        nextActivate = traceFile.getNextActivate(0);

    if (nextActivate)
        selectTransaction(nextActivate);
}

void TraceNavigator::selectNextPrecharge()
{
    shared_ptr<Transaction> nextPrecharge;

    if (!SelectedTransactions().empty())
        nextPrecharge = traceFile.getNextPrecharge(
                            SelectedTransactions().front()->Id());
    else
        nextPrecharge = traceFile.getNextPrecharge(0);

    if (nextPrecharge)
        selectTransaction(nextPrecharge);
}

void TraceNavigator::selectNextActb()
{
    shared_ptr<Transaction> nextActb;

    if (!SelectedTransactions().empty())
        nextActb = traceFile.getNextActb(SelectedTransactions().front()->Id());
    else
        nextActb = traceFile.getNextActb(0);

    if (nextActb)
        selectTransaction(nextActb);
}

void TraceNavigator::selectNextPreb()
{
    shared_ptr<Transaction> nextPreb;

    if (!SelectedTransactions().empty())
        nextPreb = traceFile.getNextPreb(
                       SelectedTransactions().front()->Id());
    else
        nextPreb = traceFile.getNextPreb(0);

    if (nextPreb)
        selectTransaction(nextPreb);
}

void TraceNavigator::selectNextRefb()
{
    shared_ptr<Transaction> n;

    if (!SelectedTransactions().empty())
        n = traceFile.getNextRefb(SelectedTransactions().front()->Id());
    else
        n = traceFile.getNextRefb(0);

    if (n)
        selectTransaction(n);
}

bool TraceNavigator::transactionIsSelected(const shared_ptr<Transaction>
                                           &transaction) const
{
    return transactionIsSelected(transaction->Id());
}

bool TraceNavigator::transactionIsSelected(ID id) const
{
    for (const auto &transaction : selectedTransactions) {
        if (transaction->Id() == id)
            return true;
    }
    return false;
}

void TraceNavigator::clearSelectedTransactions()
{
    if (hasSelectedTransactions()) {
        selectedTransactions.clear();
        Q_EMIT selectedTransactionsChanged();
    }
}

bool TraceNavigator::hasSelectedTransactions()
{
    return !selectedTransactions.empty();
}

Timespan TraceNavigator::getSpanCoveredBySelectedTransaction()
{
    if (!hasSelectedTransactions())
        return Timespan(0, 0);

    traceTime begin = SelectedTransactions().at(0)->Span().Begin();
    traceTime end = SelectedTransactions().at(0)->Span().End();

    for (const auto &transaction : selectedTransactions) {
        if (transaction->Span().End() > end)
            end = transaction->Span().End();
    }

    return Timespan(begin, end);
}
