/* -*-  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 "maarf-mac-stations.h"
#include "ns3/assert.h"
#include "ns3/log.h"
#include "ns3/default-value.h"
#include "ns3/simulator.h"

NS_LOG_COMPONENT_DEFINE ("Maarf");

#define Min(a,b) ((a<b)?a:b)
#define Max(a,b) ((a>b)?a:b)

namespace ns3 {

MaarfMacStation::MaarfMacStation (MaarfMacStations *stations,
                                  int minTimerThreshold,
                                  int minSuccessThreshold,
		    	          double successK,
			          int maxSuccessThreshold,
			          double timerK,
			          int minRtsWnd,
			          int maxRtsWnd,
			          bool rtsFailsAsDataFails,
			          bool turnOffRtsAfterRateDecrease,
				  bool turnOnRtsAfterRateIncrease)
  : m_stations (stations)
{
  m_minTimerThreshold = minTimerThreshold;
  m_timerTimeout = m_minTimerThreshold;
  m_minSuccessThreshold = minSuccessThreshold;
  m_successThreshold = m_minSuccessThreshold;
  m_successK = successK;
  m_maxSuccessThreshold = maxSuccessThreshold;
  m_timerK = timerK;
  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;
}
MaarfMacStation::~MaarfMacStation ()
{}

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

uint32_t
MaarfMacStation::GetMinTimerTimeout (void)
{
  return m_minTimerThreshold;
}

uint32_t
MaarfMacStation::GetMinSuccessThreshold (void)
{
  return m_minSuccessThreshold;
}

void
MaarfMacStation::ReportRecoveryFailure (void)
{
  SetSuccessThreshold ((int)(Min (GetSuccessThreshold () * m_successK,
                                  m_maxSuccessThreshold)));
  SetTimerTimeout ((int)(Max (GetMinTimerTimeout (),
                              GetSuccessThreshold () * m_timerK)));
}

void
MaarfMacStation::ReportFailure (void)
{
  SetTimerTimeout (GetMinTimerTimeout ());
  SetSuccessThreshold (GetMinSuccessThreshold ());
}

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



void 
MaarfMacStation::ReportRtsFailed (void)
{
  //printf ("%.9f %p RtsFail %d %d %d\n",Simulator::Now ().GetSeconds (),this,m_rate,m_timer,m_retry);
  NS_LOG_INFO ("" << this << " RtsFail rate=" << m_rate);
  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 
MaarfMacStation::ReportDataFailed (void)
{
  NS_LOG_INFO ("" << this << " TxFail rate=" << m_rate);
  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;
      ReportRecoveryFailure ();
      if (m_rate != GetMinRate ()) {
        m_rate--;
      }
      NS_LOG_INFO ("" << this << " JD rate=" << m_rate << " Sthr=" << GetSuccessThreshold ());
      //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;
      ReportFailure ();
      if (m_rate != GetMinRate ()) {
        m_rate--;
      }
      NS_LOG_INFO ("" << this << " JD rate=" << m_rate << " Sthr=" << GetSuccessThreshold ());
      //printf ("%.9f %p DecreaseRate %d\n", Simulator::Now ().GetSeconds (),this,m_rate);
    }
    if (m_retry >= 2) {
      m_timer = 0;
    }
  }
  CheckRts ();
}
void 
MaarfMacStation::ReportRxOk (double rxSnr, WifiMode txMode)
{}
void 
MaarfMacStation::ReportRtsOk (double ctsSnr, WifiMode ctsMode, double rtsSnr)
{
  NS_LOG_INFO ("" << this << " RtsOk rate=" << m_rate);
  NS_LOG_DEBUG ("self="<<this<<" rts ok");
  m_rtsCounter--;
}
void 
MaarfMacStation::ReportDataOk (double ackSnr, WifiMode ackMode, double dataSnr)
{
  NS_LOG_INFO ("" << this << " TxOk rate=" << m_rate);
  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++;
    NS_LOG_INFO ("" << this << " JI rate=" << m_rate << " Sthr=" << GetSuccessThreshold ());
    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 %d\n", Simulator::Now ().GetSeconds (),this,m_rate,(m_rtsOn?1:0));
  }
  else if (m_success == GetSuccessThreshold () ||
           m_timer >= GetTimerTimeout ()) {
    NS_LOG_INFO ("" << this << " JI rate=" << m_rate << " Sthr=" << GetSuccessThreshold ());
  }
  CheckRts ();
}
void 
MaarfMacStation::ReportFinalRtsFailed (void)
{}
void 
MaarfMacStation::ReportFinalDataFailed (void)
{}

WifiMode
MaarfMacStation::DoGetDataMode (uint32_t size)
{
  return GetSupportedMode (m_rate);
}
WifiMode
MaarfMacStation::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 
MaarfMacStation::GetTimerTimeout (void)
{
  return m_timerTimeout;
}
uint32_t 
MaarfMacStation::GetSuccessThreshold (void)
{
  return m_successThreshold;
}
void 
MaarfMacStation::SetTimerTimeout (uint32_t timerTimeout)
{
  m_timerTimeout = timerTimeout;
}
void 
MaarfMacStation::SetSuccessThreshold (uint32_t successThreshold)
{
  m_successThreshold = successThreshold;
}
MaarfMacStations *
MaarfMacStation::GetStations (void) const
{
  return m_stations;
}

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

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

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

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

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

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

bool
MaarfMacStation::NeedRts (Ptr<const Packet> packet)
{
  //printf ("%.9f %p NeedRts %d %d\n",Simulator::Now ().GetSeconds (),this,m_rate,(m_rtsOn?1:0));
  NS_LOG_INFO ("" << this << " rate=" << m_rate << " rts=" << (m_rtsOn?"RTS":"BASIC") << " rtsCounter=" << m_rtsCounter);
  return m_rtsOn;
}





MaarfMacStations::MaarfMacStations (WifiMode defaultTxMode, 
                                  uint32_t minTimerThreshold, 
				  uint32_t minSuccessThreshold, 
				  double successK,
				  uint32_t maxSuccessThreshold,
				  double timerK,
				  uint32_t minRtsWnd, 
				  uint32_t maxRtsWnd, 
				  bool rtsFailsAsDataFails,
				  bool turnOffRtsAfterRateDecrease,
				  bool turnOnRtsAfterRateIncrease)
  : MacStations (defaultTxMode),
    m_minTimerThreshold (minTimerThreshold),
    m_minSuccessThreshold (minSuccessThreshold),
    m_successK (successK),
    m_maxSuccessThreshold (maxSuccessThreshold),
    m_timerK (timerK),
    m_minRtsWnd (minRtsWnd),
    m_maxRtsWnd (maxRtsWnd),
    m_rtsFailsAsDataFails (rtsFailsAsDataFails),
    m_turnOffRtsAfterRateDecrease (turnOffRtsAfterRateDecrease),
    m_turnOnRtsAfterRateIncrease (turnOnRtsAfterRateIncrease)
{}
MaarfMacStations::~MaarfMacStations ()
{}
MacStation *
MaarfMacStations::CreateStation (void)
{
  return new MaarfMacStation (this, 
                             m_minTimerThreshold, 
			     m_minSuccessThreshold,
			     m_successK,
			     m_maxSuccessThreshold,
			     m_timerK, 
			     m_minRtsWnd, 
			     m_maxRtsWnd, 
			     m_rtsFailsAsDataFails, 
			     m_turnOffRtsAfterRateDecrease,
			     m_turnOnRtsAfterRateIncrease);
}

} // namespace ns3
