/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2004,2005,2006 INRIA
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as 
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Federico Maguolo <maguolof@dei.unipd.it>
 */

#include "mac-stations.h"
#include "marf-mac-stations.h"
#include "ns3/assert.h"
#include "ns3/log.h"
#include "ns3/default-value.h"
#include "ns3/simulator.h"

NS_LOG_COMPONENT_DEFINE ("Marf");


namespace ns3 {

MarfMacStation::MarfMacStation (MarfMacStations *stations,
                              int timerTimeout,
                              int successThreshold,
			      int minRtsWnd,
			      int maxRtsWnd,
			      bool rtsFailsAsDataFails,
			      bool turnOffRtsAfterRateDecrease,
			      bool turnOnRtsAfterRateIncrease)
  : m_stations (stations)
{
  m_timerTimeout = timerTimeout;
  m_successThreshold = successThreshold;
  m_rate = GetMinRate ();

  m_success = 0;
  m_failed = 0;
  m_recovery = false;
  m_retry = 0;
  m_timer = 0;
  m_rtsOn = false;
  m_minRtsWnd = minRtsWnd;
  m_maxRtsWnd = maxRtsWnd;
  m_rtsWnd = m_minRtsWnd;
  m_rtsCounter = 0;
  m_rtsFailsAsDataFails = rtsFailsAsDataFails;
  m_turnOffRtsAfterRateDecrease = turnOffRtsAfterRateDecrease;
  m_turnOnRtsAfterRateIncrease = turnOnRtsAfterRateIncrease;
  m_justModifyRate = true;
  m_haveASuccess = false;
}
MarfMacStation::~MarfMacStation ()
{}

uint32_t
MarfMacStation::GetMaxRate (void)
{
  return GetNSupportedModes () - 1;
}
uint32_t
MarfMacStation::GetMinRate (void)
{
  return 0;
}

bool 
MarfMacStation::NeedRecoveryFallback (void)
{
  if (m_retry >= 1) 
    {
      return true;
    } 
  else 
    {
      return false;
    }
}
bool 
MarfMacStation::NeedNormalFallback (void)
{
  int retryMod = (m_retry - 1) % 2;
  if (retryMod == 1) 
    {
      return true;
    } 
  else 
    {
      return false;
    }
}



void 
MarfMacStation::ReportRtsFailed (void)
{
  //printf ("%.9f %p RtsFail %d %d %d\n",Simulator::Now ().GetSeconds (),this,m_rate,m_timer,m_retry);
  if (m_rtsFailsAsDataFails) {
    m_rtsCounter--;
    ReportDataFailed ();
  }
}
/**
 * It is important to realize that "recovery" mode starts after failure of
 * the first transmission after a rate increase and ends at the first successful
 * transmission. Specifically, recovery mode transcends retransmissions boundaries.
 * Fundamentally, ARF handles each data transmission independently, whether it
 * is the initial transmission of a packet or the retransmission of a packet.
 * The fundamental reason for this is that there is a backoff between each data
 * transmission, be it an initial transmission or a retransmission.
 */
void 
MarfMacStation::ReportDataFailed (void)
{
  m_timer++;
  m_failed++;
  m_retry++;
  m_success = 0;
  //printf ("%.9f %p Fail %d %d %d\n",Simulator::Now ().GetSeconds (),this,m_rate,m_timer,m_retry);
  if (!m_rtsOn) {
    TurnOnRts ();
    if (!m_justModifyRate && !m_haveASuccess) {
      //printf ("%p Increase RTS Windows\n",this);
      IncreaseRtsWnd ();
    }
    else {
      //printf ("%p Reset RTS Window\n",this);
      ResetRtsWnd ();
    }
    m_rtsCounter = m_rtsWnd;
    if (m_retry >= 2) {
      m_timer = 0;
    }
    //printf ("%.9f %p AtcivateRTS %d %d\n",Simulator::Now ().GetSeconds (),this, m_rate, m_rtsCounter);
  }
  else if (m_recovery) {
    NS_ASSERT (m_retry >= 1);
    m_justModifyRate = false;
    m_rtsCounter = m_rtsWnd;
    if (NeedRecoveryFallback ()) {
      if (m_turnOffRtsAfterRateDecrease) {
        TurnOffRts ();
      }
      m_justModifyRate = true;
      if (m_rate != GetMinRate ()) {
        m_rate--;
      }
      //printf ("%.9f %p DecreaseRateRecovery %d\n", Simulator::Now ().GetSeconds (),this, m_rate);
    }
    m_timer = 0;
  } 
  else {
    NS_ASSERT (m_retry >= 1);
    m_justModifyRate = false;
    m_rtsCounter = m_rtsWnd;
    if (NeedNormalFallback ()) {
      if (m_turnOffRtsAfterRateDecrease) {
        TurnOffRts ();
      }
      m_justModifyRate = true;
      if (m_rate != GetMinRate ()) {
        m_rate--;
      }
      //printf ("%.9f %p DecreaseRate %d\n", Simulator::Now ().GetSeconds (),this,m_rate);
    }
    if (m_retry >= 2) {
      m_timer = 0;
    }
  }
  CheckRts ();
}
void 
MarfMacStation::ReportRxOk (double rxSnr, WifiMode txMode)
{}
void 
MarfMacStation::ReportRtsOk (double ctsSnr, WifiMode ctsMode, double rtsSnr)
{
  NS_LOG_DEBUG ("self="<<this<<" rts ok");
  m_rtsCounter--;
}
void 
MarfMacStation::ReportDataOk (double ackSnr, WifiMode ackMode, double dataSnr)
{
  m_timer++;
  m_success++;
  m_failed = 0;
  m_recovery = false;
  m_retry = 0;
  m_justModifyRate = false;
  m_haveASuccess = true;
  //printf ("%.9f %p Ok %d %d %d\n",Simulator::Now ().GetSeconds (),this,m_rate,m_timer,m_retry);
  //printf ("%p OK (m_success=%d, th=%d, m_rate=%d, maxRate=%d)\n",this,m_success,GetSuccessThreshold (), m_rate, GetMaxRate ());
  NS_LOG_DEBUG ("self="<<this<<" data ok success="<<m_success<<", timer="<<m_timer);
  if ((m_success == GetSuccessThreshold () ||
       m_timer >= GetTimerTimeout ()) &&
      (m_rate < GetMaxRate ())) 
  {
    NS_LOG_DEBUG ("self="<<this<<" inc rate");
    m_rate++;
    m_timer = 0;
    m_success = 0;
    m_recovery = true;
    m_justModifyRate = true;
    if (m_turnOnRtsAfterRateIncrease) {
      TurnOnRts ();
      ResetRtsWnd ();
      m_rtsCounter = m_rtsWnd;
    }
    //printf ("%.9f %p IncreaseRate %d\n", Simulator::Now ().GetSeconds (),this,m_rate);
  }
  CheckRts ();
}
void 
MarfMacStation::ReportFinalRtsFailed (void)
{}
void 
MarfMacStation::ReportFinalDataFailed (void)
{}

WifiMode
MarfMacStation::DoGetDataMode (uint32_t size)
{
  return GetSupportedMode (m_rate);
}
WifiMode
MarfMacStation::DoGetRtsMode (void)
{
  // XXX: we could/should implement the Arf algorithm for
  // RTS only by picking a single rate within the BasicRateSet.
  return GetSupportedMode (0);
}

uint32_t 
MarfMacStation::GetTimerTimeout (void)
{
  return m_timerTimeout;
}
uint32_t 
MarfMacStation::GetSuccessThreshold (void)
{
  return m_successThreshold;
}
void 
MarfMacStation::SetTimerTimeout (uint32_t timerTimeout)
{
  m_timerTimeout = timerTimeout;
}
void 
MarfMacStation::SetSuccessThreshold (uint32_t successThreshold)
{
  m_successThreshold = successThreshold;
}
MarfMacStations *
MarfMacStation::GetStations (void) const
{
  return m_stations;
}

void
MarfMacStation::CheckRts (void)
{
  if (m_rtsCounter == 0 && m_rtsOn) {
    //printf ("%p Turn off RTS\n",this);
    TurnOffRts ();
  }
}

void
MarfMacStation::TurnOffRts (void)
{
  //printf ("%.9f %p DeatcivateRTS %d %d\n",Simulator::Now ().GetSeconds (),this, m_rate, m_rtsCounter);
  m_rtsOn = false;
  m_haveASuccess = false;
}

void
MarfMacStation::TurnOnRts (void)
{
  m_rtsOn = true;
}

void
MarfMacStation::IncreaseRtsWnd (void)
{
  if (m_rtsWnd == m_maxRtsWnd)
    return;

  m_rtsWnd *= 2;
  if (m_rtsWnd > m_maxRtsWnd)
    m_rtsWnd = m_maxRtsWnd;
}

void
MarfMacStation::ResetRtsWnd (void)
{
  m_rtsWnd = m_minRtsWnd;
}

bool
MarfMacStation::NeedRts (Ptr<const Packet> packet)
{
  //printf ("%.9f %p NeedRts %d %d\n",Simulator::Now ().GetSeconds (),this,m_rate,(m_rtsOn?1:0));
  return m_rtsOn;
}





MarfMacStations::MarfMacStations (WifiMode defaultTxMode, 
                                  uint32_t timerThreshold, 
				  uint32_t successThreshold, 
				  uint32_t minRtsWnd, 
				  uint32_t maxRtsWnd, 
				  bool rtsFailsAsDataFails,
				  bool turnOffRtsAfterRateDecrease,
				  bool turnOnRtsAfterRateIncrease)
  : MacStations (defaultTxMode),
    m_timerThreshold (timerThreshold),
    m_successThreshold (successThreshold),
    m_minRtsWnd (minRtsWnd),
    m_maxRtsWnd (maxRtsWnd),
    m_rtsFailsAsDataFails (rtsFailsAsDataFails),
    m_turnOffRtsAfterRateDecrease (turnOffRtsAfterRateDecrease),
    m_turnOnRtsAfterRateIncrease (turnOnRtsAfterRateIncrease)
{}
MarfMacStations::~MarfMacStations ()
{}
MacStation *
MarfMacStations::CreateStation (void)
{
  return new MarfMacStation (this, m_timerThreshold, m_successThreshold, m_minRtsWnd, m_maxRtsWnd, m_rtsFailsAsDataFails, m_turnOffRtsAfterRateDecrease, m_turnOnRtsAfterRateIncrease);
}

} // namespace ns3
