/*
 * 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
 *    Matthias Jung
 *    Felipe S. Prado
 */

#include <algorithm>
#include <string>
#include "PowerDownManager.h"
#include "../ControllerCore.h"
#include "../TimingCalculation.h"
#include "../../../common/DebugManager.h"
#include <algorithm>
#include "../../../common/Utils.h"

using namespace tlm;
using namespace std;


PowerDownManager::PowerDownManager(sc_module_name /*name*/,
                                   ControllerCore &controller) :
    controllerCore(controller)
{
    powerDownState = PowerDownState::Awake;
    for (Bank bank : controller.getBanks()) {
        setUpDummy(powerDownPayloads[bank], bank);
    }
    //controllerCore.controller.send(PDNTrigger, sc_time_stamp(), powerDownPayloads[Bank(0)]);
}

PowerDownManager::~PowerDownManager()
{

}

void PowerDownManager::sleep(Bank /*bank*/, sc_time time)
{
    if (!canSleep() || isInPowerDown())
        return;

    PowerDownState state = powerDownState;

    if (state == PowerDownState::Awake) { //coming from active
        state = controllerCore.state->rowBufferStates->allRowBuffersAreClosed() ?
                PowerDownState::PDNPrecharge : PowerDownState::PDNActive;
    } else if (state ==
               PowerDownState::AwakeForRefresh) { //coming from refresh interrupting power down
        sc_assert(controllerCore.state->rowBufferStates->allRowBuffersAreClosed());

        if (controllerCore.state->getLastCommand(Command::PDNA).getStart()
                >= controllerCore.state->getLastCommand(Command::PDNP).getStart())
            state = PowerDownState::PDNPrecharge;
        else {
            state = PowerDownState::PDNSelfRefresh;
        }
    }

    Command cmd = IPowerDownManager::getSleepCommand(state);
    ScheduledCommand pdn(cmd, time, getMinExecutionTimeForPowerDownCmd(cmd),
                         DramExtension::getExtension(powerDownPayloads[Bank(0)]));

    controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn);

    if (state != PowerDownState::PDNSelfRefresh
            && controllerCore.refreshManager->hasCollision(pdn)) {
        return;
    } else {
        setPowerDownState(state);
        sendPowerDownPayload(pdn);
    }
}

void PowerDownManager::wakeUp(Bank bank, sc_time time)
{
    printDebugMessage("Waking up at " + time.to_string() +
                      " current power down state is " + powerDownStateToString(powerDownState));

    if (isAwakeForRefresh()) { //Request enters system during Refresh
        setPowerDownState(PowerDownState::Awake);
    } else if (isInPowerDown()) { //Request wakes up power down
        Command cmd = IPowerDownManager::getWakeUpCommand(powerDownState);
        ScheduledCommand pdn(cmd, time, getExecutionTime(cmd,
                                                         powerDownPayloads[Bank(0)]),
                             DramExtension::getExtension(powerDownPayloads[Bank(0)]));
        controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn);

        if (cmd == Command::SREFX) {
            // Leaving Self Refresh. Plan the next refresh.
            controllerCore.refreshManager->reInitialize(bank, pdn.getEnd());
            printDebugMessage("Waking up. Leaving Self Refresh at " + time.to_string() +
                              " next refresh planned to " + pdn.getEnd().to_string());
        }

        setPowerDownState(PowerDownState::Awake);

        printDebugMessage("Sending power down exit command " + commandToString(
                              cmd) + " on all banks");
        sendPowerDownPayload(pdn);
    }

    printDebugMessage("Awaken at " + time.to_string() +
                      " current power down state is " + powerDownStateToString(powerDownState));
}

void PowerDownManager::wakeUpForRefresh(Bank /*bank*/, sc_time time)
{
    printDebugMessage("Waking up for refresh at " + time.to_string() +
                      " current power down state is " + powerDownStateToString(powerDownState));

    if (isInPowerDown()) {
        Command cmd = IPowerDownManager::getWakeUpCommand(powerDownState);
        ScheduledCommand pdn(cmd, time, getExecutionTime(cmd,
                                                         powerDownPayloads[Bank(0)]),
                             DramExtension::getExtension(powerDownPayloads[Bank(0)]));

        setPowerDownState(PowerDownState::AwakeForRefresh);

        printDebugMessage("Sending power down exit command " + commandToString(
                              cmd) + " on all banks");
        sendPowerDownPayload(pdn);
    }

    printDebugMessage("Awaken for refresh at " + time.to_string() +
                      " current power down state is " + powerDownStateToString(powerDownState));
}

void PowerDownManager::sendPowerDownPayload(ScheduledCommand &pdnToSend)
{
    controllerCore.state->bus.moveCommandToNextFreeSlot(pdnToSend);
    for (size_t bank = 1; bank < controllerCore.getBanks().size(); bank++) {
        tlm_generic_payload &payloadToSend = powerDownPayloads[bank];

        ScheduledCommand pdn(pdnToSend.getCommand(), pdnToSend.getStart(),
                             pdnToSend.getExecutionTime(), DramExtension::getExtension(payloadToSend));
        controllerCore.state->change(pdn);

    }
    controllerCore.state->change(pdnToSend);
    controllerCore.controller.send(pdnToSend, powerDownPayloads[Bank(0)]);
    printDebugMessage("Sending power down command " + commandToString(
                          pdnToSend.getCommand()) + " on bank " + to_string(pdnToSend.getBank().ID()) +
                      " start time " + pdnToSend.getStart().to_string() +  " end time " +
                      pdnToSend.getEnd().to_string());
}

void PowerDownManager::setPowerDownState(PowerDownState state)
{
    powerDownState = state;
    printDebugMessage("Is now in state " + powerDownStateToString(
                          powerDownState) + " on all banks");
}

bool PowerDownManager::isInPowerDown()
{
    return (powerDownState == PowerDownState::PDNActive
            || powerDownState == PowerDownState::PDNPrecharge
            || powerDownState == PowerDownState::PDNSelfRefresh);
}

bool PowerDownManager::canSleep()
{
    for (Bank bank : controllerCore.getBanks()) {
        if (!controllerCore.numberOfPayloads[bank] == 0)
            return false;
    }
    return true;
}

bool PowerDownManager::isInSelfRefresh(Bank /*bank*/)
{
    return powerDownState == PowerDownState::PDNSelfRefresh;
}

bool PowerDownManager::isAwakeForRefresh()
{
    return powerDownState == PowerDownState::AwakeForRefresh;
}

void PowerDownManager::triggerSleep(Bank bank, sc_time time)
{
    sleep(bank, time);
}

void PowerDownManager::printDebugMessage(std::string message)
{
    DebugManager::getInstance().printDebugMessage(this->name(), message);
}

