/* -*- 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/bridge-module.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 = 35;
  double m_distNodes = 10;
  int m_packetSize = 1448;
  int m_shortGuardEnabled = 1;
  int m_mcsIndex = 1;
  int m_channelWidth = 40;
  int m_numNodes = 5;
  std::string m_txAppRate = "3Mbps";
  std::string m_errorModelType = "ns3::YansErrorRateModel";
  bool m_tracing = true;

  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"));

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

  Ptr<Node> wifi_node[m_numNodes];
  for (int i = 0; i < m_numNodes; i++)
  {
      wifi_node[i] = CreateObject<Node> ();
  }
  NodeContainer nc_wireless (wifi_node[0], wifi_node[1], wifi_node[2], wifi_node[3], wifi_node[4]);

  Ptr<Node> bridge_node[4];
  for (int i = 0; i < 4; i++)
  {
      bridge_node[i] = CreateObject<Node> ();
  }
  NodeContainer nc_bridge (bridge_node[0], bridge_node[1], bridge_node[2], bridge_node[3]);

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

  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 (25));
  phyHelper.Set ("TxPowerEnd", DoubleValue (25));
  phyHelper.Set ("ShortGuardEnabled", BooleanValue (m_shortGuardEnabled));
  phyHelper.SetChannel (spectrumChannel);

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

  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);

  MobilityHelper mobilityBridge;
  Ptr<ListPositionAllocator> bridgeAlloc = CreateObject<ListPositionAllocator> ();
  bridgeAlloc->Add(Vector (0.0, 0.0, 0.0));
  bridgeAlloc->Add(Vector (0.0, 0.0, 0.0));
  bridgeAlloc->Add(Vector (0.0, 0.0, 0.0));
  bridgeAlloc->Add(Vector (0.0, 0.0, 0.0));
  mobilityBridge.SetPositionAllocator (bridgeAlloc);
  mobilityBridge.Install (nc_bridge);

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

  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;
  }

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

  WifiHelper wifi;
  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 ()));

  WifiMacHelper wifiMac;
  Ssid ssid = Ssid ("wifi-default");
  wifiMac.SetType ("ns3::StaWifiMac", "Ssid", SsidValue (ssid));

  NetDeviceContainer de_wireless;
  phyHelper.Set ("ChannelNumber", UintegerValue (38));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (1)));

  phyHelper.Set ("ChannelNumber", UintegerValue (46));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (2)));

  phyHelper.Set ("ChannelNumber", UintegerValue (54));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (3)));

  phyHelper.Set ("ChannelNumber", UintegerValue (62));
  de_wireless.Add (wifi.Install (phyHelper, wifiMac, nc_wireless.Get (4)));


  wifiMac.SetType ("ns3::ApWifiMac", "Ssid", SsidValue (ssid));

  NetDeviceContainer n0_de_wireless;
  NodeContainer n0 (wifi_node[0]);
  phyHelper.Set ("ChannelNumber", UintegerValue (38));
  n0_de_wireless.Add (wifi.Install (phyHelper, wifiMac, n0.Get (0)));

  phyHelper.Set ("ChannelNumber", UintegerValue (46));
  n0_de_wireless.Add (wifi.Install (phyHelper, wifiMac, n0.Get (0)));

  phyHelper.Set ("ChannelNumber", UintegerValue (54));
  n0_de_wireless.Add (wifi.Install (phyHelper, wifiMac, n0.Get (0)));

  phyHelper.Set ("ChannelNumber", UintegerValue (62));
  n0_de_wireless.Add (wifi.Install (phyHelper, wifiMac, n0.Get (0)));

  NetDeviceContainer n01_bridge = wifi.Install (phyHelper, wifiMac, bridge_node[0]);
  NetDeviceContainer n02_bridge = wifi.Install (phyHelper, wifiMac, bridge_node[1]);
  NetDeviceContainer n03_bridge = wifi.Install (phyHelper, wifiMac, bridge_node[2]);
  NetDeviceContainer n04_bridge = wifi.Install (phyHelper, wifiMac, bridge_node[3]);

  BridgeHelper bridge;
  bridge.Install (bridge_node[0], n01_bridge);
  bridge.Install (bridge_node[1], n02_bridge);
  bridge.Install (bridge_node[2], n03_bridge);
  bridge.Install (bridge_node[3], n04_bridge);

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

// 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;
  internet.Install (nc_wireless);

  // We've got the "hardware" in place.  Now we need to add IP addresses.
  Ipv4AddressHelper ipv4Addr;
  ipv4Addr.SetBase ("10.1.1.0", "255.255.255.0");
  ipv4Addr.Assign (de_wireless);
  ipv4Addr.SetBase ("10.1.2.0", "255.255.255.0");
  ipv4Addr.Assign (n0_de_wireless);

  //
  // Create router nodes, initialize routing database and set up the routing
  // tables in the nodes.  We excuse the bridge nodes from having to serve as
  // routers, since they don't even have internet stacks on them.
  //
  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

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

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

  ApplicationContainer ac_sinkTcp;
  ApplicationContainer sourceApp;

  ac_sinkTcp = sinkTcp.Install (nc_wireless.Get(1));
  ac_sinkTcp.Start (Seconds (30.0));
  ac_sinkTcp.Stop (Seconds (m_totalTime));

  Ptr<Node> n = nc_wireless.Get (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 = sourceHelper.Install (nc_wireless.Get(0));
  sourceApp.Start (Seconds (31.0));
  sourceApp.Stop (Seconds (m_totalTime));

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

  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 << "::5 NODES BRIDGE::" << "\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;
}

