/*
 * 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
 *    Eder F. Zulian
 */

#ifndef TLMPHASERECORDER_H
#define TLMPHASERECORDER_H

#include <iostream>
#include <ostream>
#include <string>
#include <map>
#include <algorithm>
#include <sqlite3.h>
#include <fstream>
#include <cerrno>
#include <tlm.h>
#include <systemc.h>
#include "xmlAddressdecoder.h"
#include "DebugManager.h"
#include "Utils.h"

using namespace std;

class TlmRecorder : public sc_module
{
public:
    std::string sqlScriptURI;
    std::string dbName;

    TlmRecorder(sc_module_name /*name*/, string uri, string dbname);
    ~TlmRecorder();

    void recordMCconfig(string mcconfig)
    {
        this->mcconfig = mcconfig;
    }
    void recordMemspec(string memspec)
    {
        this->memspec = memspec;
    }
    void recordTracenames(string traces)
    {
        this->traces = traces;
    }

    void recordPhase(tlm::tlm_generic_payload &trans, tlm::tlm_phase phase,
                     sc_time time);
    void recordPower(double timeInSeconds, double averagePower);
    void recordDebugMessage(std::string message, sc_time time);
    void updateDataStrobe(const sc_time &begin, const sc_time &end,
                          tlm::tlm_generic_payload &trans);
    void closeConnection();

private:

    struct Transaction {
        Transaction() {}
        Transaction(unsigned int id): id(id) {}

        unsigned int id;
        unsigned int address;
        unsigned int burstlength;
        DramExtension dramExtension;
        sc_time timeOfGeneration;
        TimeInterval timeOnDataStrobe;

        struct Phase {
            Phase(string name, sc_time begin): name(name), interval(begin, SC_ZERO_TIME) {}
            string name;
            TimeInterval interval;
        };
        std::vector<Phase> recordedPhases;

        void insertPhase(string name, sc_time begin);
        void setPhaseEnd(string name, sc_time end);
    };

    std::string mcconfig, memspec, traces;

    void prepareSqlStatements();
    void executeSqlCommand(std::string command);
    void executeSqlStatement(sqlite3_stmt *statement);

    void openDB(std::string name);
    void createTables(std::string pathToURI);
    void setUpTransactionTerminatingPhases();

    void introduceTransactionSystem(tlm::tlm_generic_payload &trans);
    void removeTransactionFromSystem(tlm::tlm_generic_payload &trans);

    void commitRecordedDataToDB();
    void insertGeneralInfo();
    void insertTransactionInDB(Transaction &recordingData);
    void insertRangeInDB(unsigned int id, const sc_time &begin, const sc_time &end);
    void insertPhaseInDB(string phaseName, const sc_time &begin, const sc_time &end,
                         unsigned int transactionID);
    void insertDebugMessageInDB(string message, const sc_time &time);

    void printDebugMessage(std::string message);

    static const int transactionCommitRate = 1000;
    vector<Transaction> recordedData;
    map<tlm::tlm_generic_payload *, Transaction> currentTransactionsInSystem;

    unsigned int totalNumTransactions;
    sc_time simulationTimeCoveredByRecording;

    std::vector<tlm::tlm_phase> transactionTerminatingPhases;
    sqlite3 *db = NULL;
    sqlite3_stmt *insertTransactionStatement, *insertRangeStatement,
                 *updateRangeStatement,
                 *insertPhaseStatement, *updatePhaseStatement, *insertGeneralInfoStatement,
                 *insertDebugMessageStatement, *updateDataStrobeStatement, *insertPowerStatement;
    std::string insertTransactionString, insertRangeString, updateRangeString,
        insertPhaseString, updatePhaseString, insertGeneralInfoString,
        insertDebugMessageString, updateDataStrobeString, insertPowerString;
};

#endif

