#include "ns3/point-to-point-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/log.h"

#include "node-stats.h"

NS_LOG_COMPONENT_DEFINE ("NodeStats");

std::map <uint32_t, uint32_t> NodeStats::m_drop_per_flow;

NodeStats::NodeStats (uint32_t node_id)
{
  NS_LOG_FUNCTION (this << node_id);
  m_nodeId = node_id;
  
  m_drop_file.open ("node-" + std::to_string(m_nodeId) + "-drop-trace.csv");
  
  m_max_queue_delay = 0;  
  m_apptx_count = 0;
  
  m_cwnd_total = 0;
  m_cwnd_samples = 0;
  m_rtt_total = 0;
  m_rtt_samples = 0;
  //std::ofstream m_cwnd_file;
  //std::ofstream m_drop_file;
  ConnectTraces ();
  m_throughput_interval = MilliSeconds (200);
  Simulator::Schedule ( m_throughput_interval, &NodeStats::ThroughputMonitor, this);

}
NodeStats::~NodeStats ()
{
  CloseFiles ();
}

void NodeStats::ThroughputMonitor ()
{
  double current_rate = (m_current_app_tx*8.0)/m_throughput_interval.GetSeconds();

  if (m_thrpt_file.is_open ())
    m_thrpt_file << Now().GetSeconds() <<"," <<  current_rate << std::endl;
  else
  {
    return;
  }
  m_current_app_tx = 0;
  Simulator::Schedule ( m_throughput_interval, &NodeStats::ThroughputMonitor, this);
    
}
void NodeStats::TrafficControlDrop (std::string context, Ptr<const QueueDiscItem> queue_item)
{
  if (m_drop_file.is_open ())
    m_drop_file << Now().GetSeconds () << "," << m_nodeId << "," << queue_item->GetTimeStamp().GetSeconds() << std::endl;

  TcpHeader tcp;
  if (queue_item->GetPacket()->PeekHeader (tcp))
  {
    NS_LOG_DEBUG ("At time: " << Now().GetSeconds() <<  " Queue Dropped a packet with  TCP Dest Port " << tcp.GetDestinationPort () << " Packet Size: " << queue_item->GetPacket()->GetSize());
    m_drop_per_flow [tcp.GetDestinationPort() % 5001]++;
  }
  m_total_drop++;
  m_queue_drop++;

}
void NodeStats::TcDropAfterDequeue (std::string context, Ptr<const QueueDiscItem> queue_item, const char* reason)
{
  NS_LOG_DEBUG("\tAfter Dequeue Reason: " << reason);
}
void NodeStats::TcDropBeforeEnqueue (std::string context, Ptr<const QueueDiscItem> queue_item, const char* reason)
{
  NS_LOG_DEBUG("\tBefore Enqueue Reason: " << reason);
}
void NodeStats::QueueDrop (std::string context, Ptr<const Packet> packet)
{
  std::cout << Now().GetSeconds() << "QueueDrop() Trace" << std::endl;
  m_total_drop++;
  m_queue_drop++;
}
void NodeStats::RttTrace (std::string context, Time oldValue, Time newValue)
{
  if (m_rtt_sample_file.is_open())
    m_rtt_sample_file << Now().GetSeconds() << "," << newValue.GetSeconds() << std::endl; 
  
  m_rtt_total += newValue.GetSeconds ();
  m_rtt_samples++;
}

void NodeStats::ReceiverApplicationRx (std::string context, Ptr< const Packet > packet, const Address &from, const Address &to)
{
  m_apprx_count++;    
}

void NodeStats::SenderApplicationTx (std::string context, Ptr <const Packet> packet)
{
  m_current_app_tx += packet->GetSize();
  m_apptx_count++;
}

void NodeStats::TxQueueSizeChange (std::string context, uint32_t before, uint32_t after)
{
  //std::cout << context << " Before: " << before << " After: " << after << std::endl;
  if (m_txqueue_size_file.is_open ())
    m_txqueue_size_file << Now().GetSeconds() << "," << after << std::endl;
  
}

void NodeStats::QueueDiscSizeChange (std::string context, uint32_t before, uint32_t after)
{
  //std::cout << context << " Before: " << before << " After: " << after << std::endl;
  std::string queue_id = context.substr (56,1);
  if (queue_id == "0" && m_queue_disc0_size_file.is_open ())
  {
    m_queue_disc0_size_file << Now().GetSeconds() << "," << after   << std::endl;
  }
  else if (queue_id == "1" && m_queue_disc1_size_file.is_open ())
  {
    m_queue_disc1_size_file << Now().GetSeconds() << "," << after   << std::endl;
  }

}

void NodeStats::DequeueTrace (std::string context, Ptr< const QueueDiscItem > item)
{
  Time stamp = item->GetTimeStamp ();
  Time delay = Now () - stamp;
  if (m_max_queue_delay < delay.GetSeconds())
  {
    m_max_queue_delay = delay.GetSeconds ();
  }
}

void NodeStats::SenderRx (std::string context, Ptr< const Packet > packet, Ptr< Ipv4 > ipv4, uint32_t interface)
{
  m_ack_count++;
}
void NodeStats::CongestionWindowTrace (std::string context, uint32_t oldValue, uint32_t newValue)
{
  if (m_cwnd_file.is_open ())
    m_cwnd_file << Now().GetSeconds() << "," << newValue << std::endl;
  
  m_cwnd_total += newValue;
  m_cwnd_samples++;
}

bool NodeStats::HasCsma ()
{
  Ptr<Node> node = NodeList::GetNode (m_nodeId);
  for (uint32_t i=0; i<node->GetNDevices(); i++)
  {
    Ptr<CsmaNetDevice> dev = DynamicCast<CsmaNetDevice> (node->GetDevice (i)); 
    if (dev) //if cast succeeded
      return true;
  }
  return false;
}

bool NodeStats::HasPointToPoint ()
{
  Ptr<Node> node = NodeList::GetNode (m_nodeId);
  for (uint32_t i=0; i<node->GetNDevices(); i++)
  {
    Ptr<PointToPointNetDevice> dev = DynamicCast<PointToPointNetDevice> (node->GetDevice (i));
    if (dev) //if cast succeeded
      return true;
  }
  return false;
}

void NodeStats::IpDropTrace (std::string context, const Ipv4Header &header, Ptr< const Packet > packet, ns3::Ipv4L3Protocol::DropReason reason, Ptr< Ipv4 > ipv4, uint32_t interface)
{
  std::cout << "IP Drop Trace!\t" << Now ().GetSeconds() << std::endl;  
  m_total_drop++;
}

void NodeStats::IpTxTrace (std::string context, Ptr< const Packet > packet, Ptr< Ipv4 > ipv4, uint32_t interface)
{
  m_number_of_departure++;
}

void NodeStats::IpRxTrace (std::string context, Ptr< const Packet > packet, Ptr< Ipv4 > ipv4, uint32_t interface)
{    
  m_number_of_arrivals++;
}   

void NodeStats::CloseFiles ()
{
  NS_LOG_FUNCTION (this);

  m_txqueue_size_file.close();
  m_rtt_sample_file.close();
  m_cwnd_file.close();
  m_drop_file.close();
  m_thrpt_file.close();
}
void NodeStats::PrintStats ()
{
  std::cout << "Time: " << Now().GetSeconds() << " Node: " <<  m_nodeId << " AppTx Packets: " << m_apptx_count << " AppRx Packets: " << m_apprx_count 
            << " AppRx ACKS: " << m_ack_count << " TotalDrop: " << m_total_drop
            << " AvgCWND: " << ((m_cwnd_samples==0) ? 0 : (m_cwnd_total/(double)m_cwnd_samples))
            << " AvgRTT: " << ((m_rtt_samples==0) ? 0 : (m_rtt_total/(double)m_rtt_samples))
            << " Arrivals: " << m_number_of_arrivals << " Departures: " << m_number_of_departure;
            
  for (uint32_t i=0 ; i<2; i++)
  {
    if (i==m_nodeId)
    {
      std::cout << " lost " << m_drop_per_flow [i] << " packets";
    }
  }
  std::cout << std::endl;
}
void NodeStats::PostStartConnectTrace ()
{
  NS_LOG_FUNCTION (this);  
  if (!HasPointToPoint()) //only for CSMA nodes
  {
    std::string node_prefix = "/NodeList/" + std::to_string (m_nodeId);
    //Connect to RttTrace to record observed round-trip times.
    Config::Connect (node_prefix + "/$ns3::TcpL4Protocol/SocketList/*/RTT", MakeCallback (&NodeStats::RttTrace, this));
    //Connect to CongestionWindowTrace to record observed TCP Congestion window in bytes. 
    Config::Connect (node_prefix + "/$ns3::TcpL4Protocol/SocketList/*/CongestionWindow", MakeCallback (&NodeStats::CongestionWindowTrace, this));

    m_rtt_sample_file.open ("node-" + std::to_string(m_nodeId) + "-rtt.csv");
    m_cwnd_file.open ("node-" + std::to_string(m_nodeId) + "-cwnd.csv");

    m_rtt_sample_file << std::fixed;
    m_cwnd_file << std::fixed;
  }
}

void NodeStats::MacPhyTxDrop (std::string context, Ptr<const Packet> packet)
{
  std::cout << Now().GetSeconds() << "\tWARNING : MAC or PHY Tx drop. " << context << std::endl;
}

void NodeStats::ConnectTraces ()
{
  NS_LOG_FUNCTION (this);
  std::string node_prefix = "/NodeList/" + std::to_string (m_nodeId);

  Config::Connect (node_prefix + "/$ns3::TrafficControlLayer/RootQueueDiscList/*/Drop",MakeCallback (&NodeStats::TrafficControlDrop, this));
  Config::Connect (node_prefix + "/$ns3::TrafficControlLayer/RootQueueDiscList/*/DropAfterDequeue",MakeCallback (&NodeStats::TcDropAfterDequeue, this));
  Config::Connect (node_prefix + "/$ns3::TrafficControlLayer/RootQueueDiscList/*/DropBeforeEnqueue",MakeCallback (&NodeStats::TcDropBeforeEnqueue, this));

  Config::Connect (node_prefix + "/DeviceList/*/TxQueue/Drop", MakeCallback(&NodeStats::QueueDrop, this));
  
  //Config::Connect (node_prefix + "/$ns3::TrafficControlLayer/RootQueueDiscList/*/Dequeue", MakeCallback(&NodeStats::DequeueTrace, this));
  
  Config::Connect (node_prefix + "/DeviceList/*/$ns3::CsmaNetDevice/MacTxDrop", MakeCallback (&NodeStats::MacPhyTxDrop,this));
  Config::Connect (node_prefix + "/DeviceList/*/$ns3::CsmaNetDevice/PhyTxDrop", MakeCallback (&NodeStats::MacPhyTxDrop,this));


  //I only want to check the queue size if there's a PointToPointNetDevice in this node.
  if (HasPointToPoint())
  { 
    Config::Connect (node_prefix + "/DeviceList/*/$ns3::PointToPointNetDevice/TxQueue/PacketsInQueue", MakeCallback(&NodeStats::TxQueueSizeChange, this));
    Config::Connect (node_prefix + "/$ns3::TrafficControlLayer/RootQueueDiscList/*/PacketsInQueue", MakeCallback(&NodeStats::QueueDiscSizeChange, this));

    m_txqueue_size_file.open ("node-" + std::to_string(m_nodeId) + "-p2p-queue.csv");
    m_queue_disc0_size_file.open ("node-" + std::to_string(m_nodeId) + "-p2p-queuedisc-0.csv");
    m_queue_disc1_size_file.open ("node-" + std::to_string(m_nodeId) + "-p2p-queuedisc-1.csv");
    m_txqueue_size_file << std::fixed; //to avoid scientific notation
    m_queue_disc0_size_file << std::fixed;
    m_queue_disc1_size_file << std::fixed;
  }
  else 
  {
    m_thrpt_file.open ("node-" + std::to_string(m_nodeId) + "-tx-throughput.csv");;  
    m_thrpt_file << std::fixed;
  }
  for (uint32_t i=0 ; i<NodeList::GetNode (m_nodeId)->GetNApplications(); i++)
  {
    Ptr<Node> n_i = NodeList::GetNode (m_nodeId);
    Ptr<Application> app_i = n_i->GetApplication (i);
    if (app_i->GetInstanceTypeId () == PacketSink::GetTypeId())
    {
      Ptr<PacketSink> sink = DynamicCast <PacketSink> (app_i);
      sink->TraceConnect ("RxWithAddresses", "", MakeCallback (&NodeStats::ReceiverApplicationRx, this));
      std::cout << "Node " << m_nodeId << " has a PacketSink" << std::endl;
    }
    else if (app_i->GetInstanceTypeId() == BulkSendApplication::GetTypeId())
    {
      Ptr<BulkSendApplication> bulk = DynamicCast <BulkSendApplication> (app_i);
      app_i->TraceConnect ("Tx","", MakeCallback (&NodeStats::SenderApplicationTx, this));

      Ptr <Ipv4L3Protocol> ip_prot = n_i->GetObject <Ipv4L3Protocol> ();
      ip_prot->TraceConnect ("Rx", std::to_string(n_i->GetId()),  MakeCallback (&NodeStats::SenderRx,this));      

      std::cout << "Node " << m_nodeId << " has a BulkSendApplication" << std::endl;
    }
  }
  //For some reason, these two traces require that the TCP applications have started and created TCP Socket. I start my application at time 0, so I'll schedule an event at NanoSeconds (1)
  Simulator::Schedule (NanoSeconds (1), &NodeStats::PostStartConnectTrace, this); 


  Config::Connect (node_prefix + "/$ns3::Ipv4L3Protocol/Drop", MakeCallback (&NodeStats::IpDropTrace, this));
  Config::Connect (node_prefix + "/$ns3::Ipv4L3Protocol/Tx", MakeCallback (&NodeStats::IpTxTrace, this));
  Config::Connect (node_prefix + "/$ns3::Ipv4L3Protocol/Rx", MakeCallback (&NodeStats::IpRxTrace, this));

}