/*
 * 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 "Utils.h"
#include <string>
#include <tlm.h>
#include <fstream>
#include "dramExtension.h"
#include "../controller/Controller.h"

using namespace std;
using namespace tinyxml2;

bool TimeInterval::timeIsInInterval(sc_time time)
{
    return (start < time && time < end);
}

bool TimeInterval::intersects(TimeInterval other)
{
    return other.timeIsInInterval(this->start)
           || this->timeIsInInterval(other.start);
}

sc_time getDistance(sc_time a, sc_time b)
{
    if (a > b)
        return a - b;
    else
        return b - a;
}

void reportFatal(std::string sender, std::string message)
{
    SC_REPORT_FATAL(sender.c_str(), message.c_str());
}

std::string phaseNameToString(tlm::tlm_phase phase)
{
    std::ostringstream oss;
    oss << phase;
    std::string str = oss.str();
    return str;
}

unsigned int queryUIntParameter(XMLElement *node, string name)
{
    int result = 0;
    XMLElement *element;
    for (element = node->FirstChildElement("parameter"); element != NULL;
            element = element->NextSiblingElement("parameter")) {
        if (element->Attribute("id") == name) {
            sc_assert(!strcmp(element->Attribute("type"), "uint"));
            XMLError __attribute__((unused)) error = element->QueryIntAttribute("value",
                                                                                &result);
            sc_assert(!error);
            return result;
        }
    }

    reportFatal("Query XML", "Parameter '" + name + "' does not exist.");
    return 0;
}

bool parameterExists(tinyxml2::XMLElement *node, std::string name)
{
    XMLElement *element;
    for (element = node->FirstChildElement("parameter"); element != NULL;
            element = element->NextSiblingElement("parameter")) {
        if (element->Attribute("id") == name) {
            return true;
        }
    }
    return false;
}

double queryDoubleParameter(XMLElement *node, string name)
{
    double result = 0;
    XMLElement *element;
    for (element = node->FirstChildElement("parameter"); element != NULL;
            element = element->NextSiblingElement("parameter")) {
        if (element->Attribute("id") == name) {
            sc_assert(!strcmp(element->Attribute("type"), "double"));
            XMLError __attribute__((unused)) error = element->QueryDoubleAttribute("value",
                                                                                   &result);
            sc_assert(!error);
            return result;
        }
    }

    reportFatal("Query XML", "Parameter '" + name + "' does not exist.");
    return 0;
}

bool queryBoolParameter(XMLElement *node, string name)
{
    bool result = false;
    XMLElement *element;// = node->FirstChildElement("parameter");
    for (element = node->FirstChildElement("parameter"); element != NULL;
            element = element->NextSiblingElement("parameter")) {
        if (element->Attribute("id") == name) {
            sc_assert(!strcmp(element->Attribute("type"), "bool"));
            XMLError __attribute__((unused)) error = element->QueryBoolAttribute("value",
                                                                                 &result);
            sc_assert(!error);
            return result;
        }
    }

    reportFatal("Query XML", "Parameter '" + name + "' does not exist.");
    return 0;
}

string queryStringParameter(XMLElement *node, string name)
{
    XMLElement *element;
    for (element = node->FirstChildElement("parameter"); element != NULL;
            element = element->NextSiblingElement("parameter")) {
        if (element->Attribute("id") == name) {
            return element->Attribute("value");
        }
    }

    reportFatal("Query XML", "Parameter '" + name + "' does not exist.");
    return 0;
}

string errorToString(XMLError error)
{
    switch (error) {
    case XML_NO_ERROR:
        return "no error";
    case XML_NO_ATTRIBUTE:
        return "NO_ATTRIBUTE";
    case XML_WRONG_ATTRIBUTE_TYPE:
        return "WRONG_ATTRIBUTE_TYPE";
    case XML_ERROR_FILE_NOT_FOUND:
        return "FILE_NOT_FOUND";
    case XML_ERROR_FILE_COULD_NOT_BE_OPENED:
        return "FILE_COULD_NOT_BE_OPENED";
    case XML_ERROR_FILE_READ_ERROR:
        return "FILE_READ_ERROR";
    case XML_ERROR_ELEMENT_MISMATCH:
        return "ERROR_ELEMENT_MISMATCH";
    case XML_ERROR_PARSING_ELEMENT:
        return "ERROR_PARSING_ELEMENT";
    case XML_ERROR_PARSING_ATTRIBUTE:
        return "ERROR_PARSING_ATTRIBUTE";
    case XML_ERROR_IDENTIFYING_TAG:
        return "ERROR_IDENTIFYING_TAG";
    case XML_ERROR_PARSING_TEXT:
        return "ERROR_PARSING_TEXT";
    case XML_ERROR_PARSING_CDATA:
        return "ERROR_PARSING_CDATA";
    case XML_ERROR_PARSING_COMMENT:
        return "ERROR_PARSING_COMMENT";
    case XML_ERROR_PARSING_DECLARATION:
        return "ERROR_PARSING_DECLARATION";
    case XML_ERROR_PARSING_UNKNOWN:
        return "ERROR_PARSING_UNKNOWN";
    case XML_ERROR_EMPTY_DOCUMENT:
        return "ERROR_EMPTY_DOCUMENT";
    case XML_ERROR_MISMATCHED_ELEMENT:
        return "ERROR_MISMATCHED_ELEMENT";
    case XML_ERROR_PARSING:
        return "ERROR_PARSING";
    case XML_CAN_NOT_CONVERT_TEXT:
        return "CAN_NOT_CONVERT_TEXT";
    case XML_NO_TEXT_NODE:
        return "NO_TEXT_NODE";
    default:
        return "";
    }
}

void loadXML(string uri, XMLDocument &doc)
{
    XMLError error = doc.LoadFile(uri.c_str());

    if (error) {
        reportFatal("Configuration", "Error loading xml from: " + uri + " "
                    + errorToString(error));
    }
}

string loadTextFileContents(string filename)
{

    ifstream in(filename.c_str(), ios::in | ios::binary);
    if (in) {
        string contents;
        in.seekg(0, ios::end);
        contents.resize(in.tellg());
        in.seekg(0, ios::beg);
        in.read(&contents[0], contents.size());
        in.close();
        return (contents);
    } else {
        reportFatal("Error loading file", "Could not load textfile from " + filename);
        return "";
    }
}

void setUpDummy(tlm::tlm_generic_payload &payload, Bank &bank)
{
    payload.set_address(bank.getStartAddress());
    payload.set_command(tlm::TLM_READ_COMMAND);
    payload.set_data_length(0);
    payload.set_response_status(tlm::TLM_OK_RESPONSE);
    payload.set_dmi_allowed(false);
    payload.set_byte_enable_length(0);
    payload.set_streaming_width(0);
    payload.set_extension(new DramExtension(Thread(
                                                Controller::ControllerThreadId()), bank, BankGroup(0), Row(0),
                                            Column(0))); //payload takes ownership
    //TODO .. Dummies muessen noch banggruppe und rank sauber bekommen .. noch was ueberlegen!!!
}

std::string getFileName(std::string uri)
{
    // Remove directory if present.
    // Do this before extension removal incase directory has a period character.
    const size_t last_slash_idx = uri.find_last_of("\\/");
    if (std::string::npos != last_slash_idx) {
        uri.erase(0, last_slash_idx + 1);
    }

    // Remove extension if present.
    const size_t period_idx = uri.rfind('.');
    if (std::string::npos != period_idx) {
        uri.erase(period_idx);
    }
    return uri;
}
