/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * 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
 *
 */

#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"
#include "ns3/v4ping-helper.h"
#include "ns3/aodv-helper.h"
#include "ns3/olsr-helper.h"
#include "ns3/csma-helper.h"
#include "ns3/flow-monitor-helper.h"
#include "ns3/ipv4-flow-classifier.h"
#include "ns3/flow-monitor.h"
#include "ns3/spectrum-helper.h"
#include "ns3/antenna-model.h"
#include "ns3/spectrum-wifi-phy.h"
#include "ns3/spectrum-wifi-helper.h"
#include "ns3/propagation-loss-model.h"
#include "ns3/multi-model-spectrum-channel.h"
#include "ns3/angles.h"
#include "ns3/vector.h"
#include <sstream>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>


using namespace ns3;

int main (int argc, char *argv[])
{
  double m_totalTime = 50;
  double m_distNodes = 10;
  int m_packetSize = 1448;
  int m_shortGuardEnabled = 1;
  int m_mcsIndex = 8;
  int m_channelWidth = 80;
  int m_numNodes = 5;
  std::string m_txAppRate = "3Mbps";
  std::string m_errorModelType = "ns3::YansErrorRateModel";
  bool m_tracing = false;

  CommandLine cmd;
  cmd.AddValue ("m_totalTime", "Total simulation time in seconds", m_totalTime);
  cmd.AddValue ("m_distNodes", "Distance between the nodes in meters", m_distNodes);
  cmd.AddValue ("m_packetSize", "Size of application packet in bytes", m_packetSize);
  cmd.AddValue ("m_shortGuardEnabled", "Whether short guard is enabled or not", m_shortGuardEnabled);
  cmd.AddValue ("m_mcsIndex", "MCS index of 802.11ac transmission", m_mcsIndex);
  cmd.AddValue ("m_channelWidth", "Channel width of 802.11ac transmission", m_channelWidth);
  cmd.AddValue ("m_numNodes", "Number of nodes", m_numNodes);
  cmd.AddValue ("m_txAppRate", "Set speed of traffic generation", m_txAppRate);
  cmd.AddValue ("m_errorModelType", "Type of error model used", m_errorModelType);
  cmd.AddValue ("m_tracing", "Turn on routing table tracing", m_tracing);
  cmd.Parse (argc, argv);

  /*Time::SetResolution (Time::NS);
  LogComponentEnable ("SpectrumWifiPhy", LOG_LEVEL_DEBUG);
  LogComponentEnable ("Ipv4StaticRoutingHelper", LOG_LEVEL_DEBUG);*/

  // disable fragmentation for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  NodeContainer nc_wireless;
  nc_wireless.Create (m_numNodes);

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  SpectrumWifiPhyHelper phyHelper = SpectrumWifiPhyHelper::Default ();
  phyHelper.SetPcapDataLinkType (SpectrumWifiPhyHelper::DLT_IEEE802_11_RADIO);
  Config::SetDefault ("ns3::WifiPhy::CcaMode1Threshold", DoubleValue (-62.0));

  Ptr<MultiModelSpectrumChannel> spectrumChannel = CreateObject<MultiModelSpectrumChannel> ();

  Ptr<FriisPropagationLossModel> lossModel = CreateObject<FriisPropagationLossModel> ();
  spectrumChannel->AddPropagationLossModel (lossModel);

  Ptr<ConstantSpeedPropagationDelayModel> delayModel = CreateObject<ConstantSpeedPropagationDelayModel> ();
  spectrumChannel->SetPropagationDelayModel (delayModel);

  phyHelper.SetErrorRateModel (m_errorModelType);
  phyHelper.Set ("TxPowerStart", DoubleValue (38));
  phyHelper.Set ("TxPowerEnd", DoubleValue (38));
  phyHelper.Set ("ShortGuardEnabled", BooleanValue (m_shortGuardEnabled));
  phyHelper.SetChannel (spectrumChannel);

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  WifiHelper wifi;

  WifiMacHelper wifiMac;
  wifi.SetStandard (WIFI_PHY_STANDARD_80211ac);
  std::ostringstream oss;
  oss << "VhtMcs" << m_mcsIndex;
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue (oss.str ()),
                                "ControlMode", StringValue (oss.str ()));

  wifiMac.SetType ("ns3::AdhocWifiMac");

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  MobilityHelper mobilityWireless;
  Ptr<ListPositionAllocator> wirelessAlloc = CreateObject<ListPositionAllocator> ();
  wirelessAlloc->Add(Vector (0.0, 0.0, 0.0));
  wirelessAlloc->Add(Vector (0.0, -1*m_distNodes, 0.0));
  wirelessAlloc->Add(Vector (-1*m_distNodes, 0.0, 0.0));
  wirelessAlloc->Add(Vector (0.0, 1*m_distNodes, 0.0));
  wirelessAlloc->Add(Vector (1*m_distNodes, 0.0, 0.0));
  mobilityWireless.SetPositionAllocator (wirelessAlloc);
  mobilityWireless.Install (nc_wireless);

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  Ptr<MobilityModel> mob[m_numNodes];
  Vector pos[m_numNodes];

  for (int i = 0; i < m_numNodes; i++)
  {
      mob[i] = nc_wireless.Get(i)->GetObject<MobilityModel>();         // Node i
      pos[i] = mob[i]->GetPosition ();
      std::cout << "Position of node " << nc_wireless.Get(i)->GetId () << ":" << " x=" << pos[i].x << ", y=" << pos[i].y
      << std::endl;
  }


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  NetDeviceContainer de_wireless;
  phyHelper.Set ("ChannelNumber", UintegerValue (42));

  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (0)));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (1)));

  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (0)));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (2)));

  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (0)));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (3)));

  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (0)));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (4)));

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Channel width must be set *after* installation because the attribute is overwritten by the ConfigureStandard method ()
  Config::Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", UintegerValue (m_channelWidth));

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  InternetStackHelper internet;
  //AodvHelper aodv;
  OlsrHelper olsr;
  //internetStack.SetRoutingHelper (aodv);
  internet.SetRoutingHelper (olsr);
  internet.Install (nc_wireless);

  Ipv4AddressHelper addrWireless;
  addrWireless.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer if_wireless = addrWireless.Assign (de_wireless);

  Ptr<Ipv4> ip_wireless[m_numNodes];
  for (int i = 0; i < m_numNodes; i++)
  {
      ip_wireless[i] = nc_wireless.Get(i)->GetObject<Ipv4> ();
  }

  Ipv4StaticRoutingHelper ipv4RoutingHelper;
  Ptr<Ipv4StaticRouting> staticRouting[m_numNodes];
  for (int i = 0; i < m_numNodes; i++)
  {
      staticRouting[i] = ipv4RoutingHelper.GetStaticRouting (ip_wireless[i]);
  }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  PacketSinkHelper sinkTcp ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), 9));

  ApplicationContainer ac_sinkTcp[4];
  ApplicationContainer sourceApp[4];

  for (int i = 0; i < 4; i++)
  {
      ac_sinkTcp[i] = sinkTcp.Install (nc_wireless.Get(i+1));
      ac_sinkTcp[i].Start (Seconds (30.0 + i * 0.1));
      ac_sinkTcp[i].Stop (Seconds (m_totalTime));

      Ptr<Node> n = nc_wireless.Get (i+1);
      Ptr<Ipv4> ipv4 = n->GetObject<Ipv4> ();
      Ipv4InterfaceAddress ipv4_int_addr = ipv4->GetAddress (1, 0);
      Ipv4Address ip_addr = ipv4_int_addr.GetLocal ();
      OnOffHelper sourceHelper ("ns3::TcpSocketFactory", Address (InetSocketAddress (ip_addr, 9)));

      sourceHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
      sourceHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));
      sourceHelper.SetAttribute ("DataRate", DataRateValue (m_txAppRate)); //bit/s
      sourceHelper.SetAttribute ("PacketSize", UintegerValue(m_packetSize));

      sourceApp[i] = sourceHelper.Install (nc_wireless.Get(0));
      sourceApp[i].Start (Seconds (30.5 + i * 0.1));
      sourceApp[i].Stop (Seconds (m_totalTime));
  }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  if (m_tracing == true)
    {
      Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("olsr.routes", std::ios::out);
      ipv4RoutingHelper.PrintRoutingTableAllEvery (Seconds (1), routingStream);

      Ptr<OutputStreamWrapper> neighborStream = Create<OutputStreamWrapper> ("olsr.neighbors", std::ios::out);
      ipv4RoutingHelper.PrintNeighborCacheAllEvery (Seconds (1), neighborStream);
    }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  FlowMonitorHelper flowmon;
  Ptr<FlowMonitor> monitor = flowmon.InstallAll ();

  Simulator::Stop (Seconds (m_totalTime));
  Simulator::Run ();

  monitor->CheckForLostPackets ();
  Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ());
  FlowMonitor::FlowStatsContainer stats = monitor->GetFlowStats ();

  Time runTime;
  runTime = Seconds(m_totalTime);

  for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator i = stats.begin (); i != stats.end(); ++i)
  {
    if (i->first > 0) // flow number
      {
        Ipv4FlowClassifier::FiveTuple t=classifier->FindFlow (i->first);
        std::cout << "\nFlow " << i->first  << " (" << t.sourceAddress << " -> " << t.destinationAddress << ")\n";
        std::cout << "  Simulation Time: " << m_totalTime << "\n";
        std::cout << "  Tx Packets: " << i->second.txPackets << "\n";
        std::cout << "  Tx Bytes:   " << i->second.txBytes << "\n";
        std::cout << "  Tx Offered:  " << i->second.txBytes * 8.0 / (runTime.GetSeconds ()) / 1000 / 1000 << " Mbps\n";
        std::cout << "  Rx Packets: " << i->second.rxPackets << "\n";
        std::cout << "  Rx Bytes:   " << i->second.rxBytes << "\n";
        std::cout << "  Lost Packets:   " << i->second.lostPackets << "\n";
        if (i->second.rxPackets > 1)
        {
            std::cout << "  Delay:   " << ((i->second.delaySum)/(i->second.rxPackets))/1000000 << "\n";         //ms
            std::cout << "  Jitter:   " << ((i->second.jitterSum)/(i->second.rxPackets)) << "\n";       //ns
        }
        std::cout << "  Throughput: " << i->second.rxBytes * 8.0 / (runTime.GetSeconds ()) /1000 / 1000 << " Mbps\n";
        std::cout << "******" << "\n";
      }
  }

  std::cout << "::OLSR::" << "\n";
  std::cout << "Total time: " << m_totalTime << "\n";
  std::cout << "Number of nodes: " << m_numNodes << "\n";
  std::cout << "Inter-node distance: " << m_distNodes << "\n";
  std::cout << "Packet size: " << m_packetSize << "\n";
  std::cout << "Short guard enabled: " << m_shortGuardEnabled << "\n";
  std::cout << "MCS index: " << m_mcsIndex << "\n";
  std::cout << "Channel width: " << m_channelWidth << "\n";
  std::cout << "Application rate: " << m_txAppRate << "\n";
  std::cout << "Error model type: " << m_errorModelType << "\n";
  std::cout << "Tracing enabled: " << m_tracing << "\n";
  std::cout << "******" << "\n";

  Simulator::Destroy ();

  return 0;
}

