#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/netanim-module.h"
#include "ns3/traffic-control-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/log.h"
#include "color-printing.h"
#include "node-stats.h"
#include <regex>
#include "ns3/flow-monitor-module.h"
#include "ns3/stats-module.h"
#include <map> 
#include <fstream>
#include <chrono>

using namespace ns3;
void SetTrafficQueue (Ptr<Node> n, std::string queue_type)
{
  for (uint32_t i=0 ; i<n->GetNDevices(); i++)
  {
    Ptr<NetDevice> device = n->GetDevice (i);
    Ptr<TrafficControlLayer> tc = n->GetObject <TrafficControlLayer> ();
    if (DynamicCast<LoopbackNetDevice> (device) == 0)
      {
        tc->DeleteRootQueueDiscOnDevice (device);

        Ptr<NetDeviceQueueInterface> ndqi = device->GetObject<NetDeviceQueueInterface> ();
        // It is useless to install a queue disc if the device has no
        // NetDeviceQueueInterface attached: the device queue is never
        // stopped and every packet enqueued in the queue disc is
        // immediately dequeued, hence there will never be backlog
        if (ndqi)
          {
            std::size_t nTxQueues = ndqi->GetNTxQueues ();
            //NS_LOG_LOGIC ("Installing default traffic control configuration ("<< nTxQueues << " device queue(s))");
            TrafficControlHelper tcHelper;
            /*
            If you want to set Queuing Discipline (QueueDisc) attributes, pass a list of attributes and values

            For example, 
              tcHelper.SetRootQueueDisc ("ns3::FqCoDelQueueDisc", "UseEcn", BooleanValue(true))
            */
            tcHelper.SetRootQueueDisc (queue_type);
            tcHelper.Install (device);
          }
      }
  }
}

int main (int argc, char *argv[])
{
  CommandLine cmd;

  uint32_t n1 = 2;
  uint32_t n2 = 2;
  double simulation_time = 20; // 10 seconds
  double client_start_time = 0; //8 seconds
  double client_end_time = 19;
  int queue_size = 200;
  std::string queue_disc = "fifo";
  cmd.AddValue ("t", "Simulation time in seconds", simulation_time);
  cmd.AddValue ("qsize", "Queue size in Packets", queue_size);
  cmd.AddValue ("qdisc", "Queue size in Packets", queue_disc);
  cmd.AddValue ("cs", "Client Start time", client_start_time);
  cmd.AddValue ("ce", "Client End time", client_end_time);
  cmd.Parse (argc, argv);
  
  client_end_time = simulation_time-1;
  /**
   The network looks like this

   n0--|           |--n2
       |--n4---n5--|
   n1--|           |--n3
      LAN1        LAN2

   n0 sends data to n2
   n1 sends data to n3
   n4 is part of LAN1, and has two net device of type PointToPointNetDevice & CsmaNetDevice
   n5 is part of LAN2, and has PointToPointNetDevice & CsmaNetDevice as well.
  */

  //For the first network
  NodeContainer lan1_nodes;

  //For the second network
  NodeContainer lan2_nodes;

  //for the nodes in the middle.
  NodeContainer router_nodes;

  lan1_nodes.Create (n1);
  lan2_nodes.Create (n2);
  router_nodes.Create (2);
  
  //We create a NodeContainer to nodes that only have Csma (Ethernet) device.
  NodeContainer csma_only_nodes1, csma_only_nodes2;
  csma_only_nodes1.Add (lan1_nodes);
  csma_only_nodes2.Add (lan2_nodes);

  //Let's create LAN 1 by attaching a CsmaNetDevice to all the nodes on the LAN
  CsmaHelper csma1;
  csma1.SetChannelAttribute ("DataRate", StringValue ("1Gbps"));
  csma1.SetChannelAttribute ("Delay", TimeValue (MicroSeconds (20)));
  //Router 1 is accessible on LAN 1, so we add it to the list nodes.
  lan1_nodes.Add (router_nodes.Get (0));
  //Actually attaching CsmaNetDevice to all LAN 1 nodes.
  NetDeviceContainer lan1Devices;
  lan1Devices = csma1.Install (lan1_nodes);

  //Doing the same for LAN 2
  CsmaHelper csma2;
  /*
  For "DataRate", you can use DataRateValue (DataRate (1000000000)) and StringValue ("1Gbps")
  */
  csma2.SetChannelAttribute ("DataRate", StringValue ("1Gbps"));
  csma2.SetChannelAttribute ("Delay", TimeValue (MicroSeconds (20)));
  
  //Router 2 is on LAN 2, so we add it to the node container
  lan2_nodes.Add (router_nodes.Get (1));

  NetDeviceContainer lan2Devices;
  lan2Devices = csma2.Install (lan2_nodes);

  //Set the default queue size to 200 packets
  QueueSize qs (QueueSizeUnit::PACKETS, queue_size);
  QueueSizeValue newSize = QueueSizeValue (qs);
  Config::SetDefaultFailSafe ("ns3::DropTailQueue<Packet>::MaxSize", newSize );
  Config::SetDefaultFailSafe ("ns3::QueueBase::MaxSize", newSize );
  Config::SetDefaultFailSafe ("ns3::FifoQueueDisc::MaxSize", newSize);
  Config::SetDefaultFailSafe ("ns3::RedQueueDisc::MaxSize", newSize);
  Config::SetDefaultFailSafe ("ns3::CoDelQueueDisc::MaxSize", newSize);
  Config::SetDefaultFailSafe ("ns3::FqCoDelQueueDisc::MaxSize", newSize);

  
  //Config::SetDefault ("ns3::TcpL4Protocol::SocketType", TypeIdValue(ns3::TcpIllinois::GetTypeId()));

  /* So far our two LANs are disjoint, r1 and r2 need to be connected */
  //A PointToPoint connection between the two routers
  PointToPointHelper pointToPoint;
  /**
   * We can set the "DataRate" to StringValue("1Mbps"), DataRateValue(DataRate ("10Mbps")) or DataRateValue(DataRate (1000000))
   * When we use DataRateValue, the value is in bps.
   */
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue("10Mbps") ); 
  /**
   * We can set the "Delay" to StringValue ("2ms"), TimeValue (MilliSeconds(2)), 
   */ 
  pointToPoint.SetChannelAttribute ("Delay", TimeValue (MilliSeconds(20)));
  
  NetDeviceContainer firstHopLinkDevs;
  firstHopLinkDevs = pointToPoint.Install (router_nodes.Get(0), router_nodes.Get(1));


  //Packet::EnablePrinting ();

  //Setting IP addresses. Notice that router 1 & 2 are in LAN 1 & 2 respectively.
  InternetStackHelper stack;
  stack.InstallAll ();

  Ipv4AddressHelper address;
  
  //For LAN 1
  address.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer lan1interfaces;
  lan1interfaces = address.Assign (lan1Devices);
  //For LAN 2
  address.SetBase ("10.1.2.0", "255.255.255.0");
  Ipv4InterfaceContainer lan2interfaces;
  lan2interfaces = address.Assign (lan2Devices);
  //For PointToPoint
  address.SetBase ("10.1.100.0", "255.255.255.0");
  Ipv4InterfaceContainer routerInterfaces;
  routerInterfaces = address.Assign (firstHopLinkDevs);
  
  //setting up TCP
  uint16_t port1 = 5001;
  uint16_t port2 = 5002;
  BulkSendHelper sourceHelper ("ns3::TcpSocketFactory",
                               InetSocketAddress (lan2interfaces.GetAddress (0), port1));
  sourceHelper.SetAttribute ("MaxBytes", UintegerValue (0));
  sourceHelper.SetAttribute ("SendSize", UintegerValue (1000));
  
  ApplicationContainer sourceApp = sourceHelper.Install (csma_only_nodes1);
  sourceApp.Start (Seconds (client_start_time));
  sourceApp.Stop (Seconds (client_end_time));
  
  //Setting a different target IP & port for the 2nd application 
  
  Ptr<BulkSendApplication> ps = DynamicCast<BulkSendApplication> (sourceApp.Get(1));
  AddressValue av (InetSocketAddress (lan2interfaces.GetAddress (1), port2));
  ps->SetAttribute ("Remote", av);
  

  PacketSinkHelper sinkHelper ("ns3::TcpSocketFactory",
                         InetSocketAddress (Ipv4Address::GetAny (), port1));
  ApplicationContainer sinkApp = sinkHelper.Install (csma_only_nodes2);
  sinkApp.Start (Seconds (0.0));
  sinkApp.Stop (Seconds (simulation_time));
  
  //Setting a different port number for the 2nd sink application
  Ptr<PacketSink> sink = DynamicCast<PacketSink> (sinkApp.Get (1));
  AddressValue target_port (InetSocketAddress (Ipv4Address::GetAny (), port2));
  sink->SetAttribute ("Local", target_port);

  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

  
  for(uint32_t i=0; i<NodeList::GetNNodes(); i++)
  {
    if (queue_disc == "fifo")
    {
      SetTrafficQueue (NodeList::GetNode(i), "ns3::FifoQueueDisc");
    }
    else if (queue_disc == "codel")
    {
      SetTrafficQueue (NodeList::GetNode(i), "ns3::CoDelQueueDisc");  
    }
    else if (queue_disc == "fqcodel")
    {
      SetTrafficQueue (NodeList::GetNode(i), "ns3::FqCoDelQueueDisc");    
    }
    else if (queue_disc == "red")
    {
      SetTrafficQueue (NodeList::GetNode(i), "ns3::RedQueueDisc");    
    }

  }

  //To enable packet->ToString() function to print information. Commented for efficiency
  //Packet::EnablePrinting ();

  // Below, there are three methods to collect data. One is user-defined in a class named NodeStats, the others are built-in ns-3

  //I created a class NodeStats, that stores stats for nodes.
  std::map<uint32_t,NodeStats*> stats;
  for (uint32_t i=0 ; i<NodeList::GetNNodes(); i++)
  {
    NodeStats* stats_i = new NodeStats(i);
    stats [i] = stats_i;
  }

  //Another way to collect information of IPv4 is to use FlowMonitor as follows  
  Ptr<FlowMonitor> flowMonitor;
  FlowMonitorHelper flowHelper;
  flowMonitor = flowHelper.InstallAll();

  //ns-3 also has file helper which works with TraceSources to generate files.
  //std::string source_path = "/Nodes/*/DeviceList/*/$ns3::PointToPointNetDevice/TxQueue/PacketsInQueue";
  /*
  FileHelper fileHelper;
  fileHelper.ConfigureFile ("tx-queue", FileAggregator::COMMA_SEPARATED);
  fileHelper.Set2dFormat ("%.3f, %d");
  fileHelper.WriteProbe ("ns3::Uinteger32Probe",source_path,"Output");
  */


  Simulator::Stop (Seconds(simulation_time));
  //Starting simulation
  Simulator::Run ();

  //Save FlowMonitor info to an XML file. The first true parameter adds
  flowMonitor->SerializeToXmlFile("competing-flows.xml", true, true);

  //We can use FlowMonitor Stats
  FlowMonitor::FlowStatsContainer fff = flowMonitor->GetFlowStats ();
  std::cout << "\nPrinting FlowMonitor Information\n" << std::endl;
  for (FlowMonitor::FlowStatsContainer::iterator it = fff.begin (); it!=fff.end(); ++it )
  {
    FlowMonitor::FlowStats stats = it->second;
  
    std::cout << "Flow ID: " << it->first << " TxPacket: " << stats.txPackets << " TxBytes: " << stats.txBytes 
              << " RxPacket: " << stats.rxPackets << " RxBytes: " << stats.rxBytes 
              << " Lost Packets: " << stats.lostPackets
              << std::endl;

  }
  std::cout << std::endl;

  std::cout << "\nPrinting Stats from NodeStats class\n" << std::endl;

  //After simulation concludes, I am going to print stats for nodes 0,1 (the senders) and node 4 (the first router)
  stats [0]->PrintStats ();
  stats [1]->PrintStats ();
  stats [4]->PrintStats ();
  
  for (uint32_t i=0 ; i<NodeList::GetNNodes(); i++)
  {
    stats [i]->CloseFiles ();
    delete stats[i];
  }
  
 

  Simulator::Destroy ();
  return 0;
}