/*
 * 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
 */

#ifndef TRACEDB_H
#define TRACEDB_H

#include<string>
#include<exception>
#include<QString>
#include<QSqlDatabase>
#include<QSqlQuery>
#include<QSqlTableModel>
#include<vector>
#include <string>
#include "businessObjects/transaction.h"
#include "businessObjects/generalinfo.h"
#include "businessObjects/phases/phasefactory.h"
#include "businessObjects/comment.h"
#include "QueryTexts.h"

/*  TraceDB handles the connection to a SQLLite database containing trace data.
 *  A TraceDB object always holds an open connection to a valid database.
 */

class TraceDB : public QObject
{
    Q_OBJECT

public:
    TraceDB(QString path, bool openExisting);
    const QString &getPathToDB()
    {
        return pathToDB;
    }

    void updateComments(std::vector<Comment> comments);
    void updateFileDescription(const QString &description);
    void refreshData();

    const GeneralInfo &getGeneralInfo()
    {
        return generalInfo;
    }

    std::vector<std::shared_ptr<Transaction>> getTransactionsWithCustomQuery(
                                               QString queryText);
    std::vector<std::shared_ptr<Transaction>> getTransactionsInTimespan(
                                               const Timespan &span);
    std::shared_ptr<Transaction> getNextPrecharge(ID currentTransactionId);
    std::shared_ptr<Transaction> getNextActivate(ID currentTransactionId);
    std::shared_ptr<Transaction> getNextRefresh(ID currentTransactionId);
    std::shared_ptr<Transaction> getNextPreb(ID currentTransactionId);
    std::shared_ptr<Transaction> getNextActb(ID currentTransactionId);
    std::shared_ptr<Transaction> getNextRefb(ID currentTransactionId);


    std::shared_ptr<Transaction> getTransactionByID(ID id);
    ID getTransactionIDFromPhaseID(ID phaseID);

    std::vector<Comment> getComments();
    std::vector<Comment> getDebugMessagesInTimespan(const Timespan &span);
    std::vector<Comment> getDebugMessagesInTimespan(const Timespan &span,
                                                    unsigned int limit);

private:
    QString pathToDB;
    QSqlDatabase database;
    GeneralInfo generalInfo;

    QSqlQuery insertPhaseQuery;
    QSqlQuery insertTransactionQuery;
    QSqlQuery selectTransactionsByTimespan;
    QSqlQuery selectTransactionById;
    QSqlQuery selectDebugMessagesByTimespan;
    QSqlQuery selectDebugMessagesByTimespanWithLimit;

    TransactionQueryTexts queryTexts;
    void prepareQueries();
    void executeQuery(QSqlQuery query);
    QString queryToString(QSqlQuery query);
    std::shared_ptr<Transaction> parseTransactionFromQuery(QSqlQuery &query);
    std::vector<std::shared_ptr<Transaction>> parseTransactionsFromQuery(
                                               QSqlQuery &query);
    std::vector<Comment> parseCommentsFromQuery(QSqlQuery &query);

    void executeScriptFile(QString fileName);
    void dropAndCreateTables();

    unsigned int getNumberOfPhases();
    GeneralInfo getGeneralInfoFromDB();
};



class sqlException : public std::exception
{
private:
    std::string message;
public:
    sqlException(std::string message, std::string filename)
    {
        this->message = std::string("Error in file ") + filename + std::string(" ") +
                        message;
    }
    const char *what() const noexcept
    {
        return message.c_str();
    }
};
#endif // TRACEDB_H



