#include "modules.hpp"

/**
 * Create a sensors cell base on
 * nbSensors Number of temperature sensors in the cell
 * ap the Access Point (usually linked to the cloud)
 */
Cell createCell(uint32_t nbSensors, Ptr<ns3::Node> ap){
  // Create sensors
  NodeContainer sensors;
  sensors.Create(nbSensors);

  // Place nodes somehow, this is required by every wireless simulation
  for (uint32_t i = 0; i < nbSensors; i++)
    {
      sensors.Get (i)->AggregateObject (CreateObject<ConstantPositionMobilityModel> ());
    }
  ap->AggregateObject (CreateObject<ConstantPositionMobilityModel> ());

  // To apply XXWifiPhy and WifiMac on sensors 
  WifiHelper wifiHelper;
  wifiHelper.SetStandard (WIFI_PHY_STANDARD_80211n_5GHZ);

  /* Set up Legacy Channel */
  YansWifiChannelHelper wifiChannel;
  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
  wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel", "Frequency", DoubleValue (5e9));

  /* Setup Physical Layer */
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  wifiPhy.SetChannel (wifiChannel.Create ());
  wifiPhy.Set ("TxPowerStart", DoubleValue (10.0));
  wifiPhy.Set ("TxPowerEnd", DoubleValue (10.0));
  wifiPhy.Set ("TxPowerLevels", UintegerValue (1));
  wifiPhy.Set ("TxGain", DoubleValue (0));
  wifiPhy.Set ("RxGain", DoubleValue (0));
  wifiPhy.Set ("RxNoiseFigure", DoubleValue (10));
  wifiPhy.Set ("CcaMode1Threshold", DoubleValue (-79));
  wifiPhy.Set ("EnergyDetectionThreshold", DoubleValue (-79 + 3));
  //  wifiPhy.SetErrorRateModel ("ns3::YansErrorRateModel");
  wifiHelper.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                      "DataMode", StringValue ("HtMcs7"),
                                      "ControlMode", StringValue ("HtMcs0"));
  /* Configure AP */
  Ssid ssid = Ssid ("network");
  WifiMacHelper wifiMac;
  wifiMac.SetType ("ns3::ApWifiMac", "Ssid", SsidValue (ssid));
  NetDeviceContainer apNetDevice;
  apNetDevice = wifiHelper.Install (wifiPhy, wifiMac, ap);
  /* Configure STA */
  wifiMac.SetType ("ns3::StaWifiMac", "Ssid", SsidValue (ssid));
  NetDeviceContainer sensorsNetDevices;
  sensorsNetDevices = wifiHelper.Install (wifiPhy, wifiMac, sensors);

  return(std::make_pair(std::make_pair(ap,sensors),std::make_pair(apNetDevice,sensorsNetDevices)));
}

/**
 * Install network stack and applications
 */
void setupScenario(Cell cell, CloudInfos cloudInfos, int sensorsPktSize, int sensorsSendInterval){
  NodeContainer ap=cell.first.first;
  NodeContainer sensors=cell.first.second;
  NetDeviceContainer apNetDev= cell.second.first;
  NetDeviceContainer sensorsNetDev= cell.second.second;
  
  // 6. Install TCP/IP stack & assign IP addresses
  InternetStackHelper internet;
  //  internet.Install (ap);
  internet.Install (sensors);
  Ipv4AddressHelper ipv4;
  ipv4.SetBase ("10.0.0.0", "255.255.0.0");
  Ipv4InterfaceContainer apInt,sensorsInt;
  apInt=ipv4.Assign(apNetDev);
  sensorsInt=ipv4.Assign(sensorsNetDev);

  UdpEchoClientHelper echoClientHelper (InetSocketAddress (cloudInfos.second.first, cloudInfos.second.second));
  //  echoClientHelper.SetAttribute ("MaxPackets", UintegerValue (10));
  echoClientHelper.SetAttribute ("Interval", TimeValue (Seconds (sensorsSendInterval)));
  echoClientHelper.SetAttribute ("PacketSize", UintegerValue (sensorsPktSize));
  ApplicationContainer pingApps;

  // again using different start times to workaround Bug 388 and Bug 912
  echoClientHelper.SetAttribute ("StartTime", TimeValue (Seconds (1))); // Start at 1 (WIFI seems to not work when t<1)
  echoClientHelper.Install (sensors);
}


CloudInfos createCloud(int nbHop, uint32_t bandwidth, uint32_t latency){
 
  NodeContainer HopNodes;
  HopNodes.Create(nbHop);
  InternetStackHelper stack;
  stack.Install(HopNodes);

  Ipv4Address cloudIP; // Will be fill in the following for loop
  int cloudPort=80;
  for(int i=0;i<nbHop-1;i++){
    NodeContainer curNodes(HopNodes.Get(i),HopNodes.Get(i+1));

    PointToPointHelper pointToPoint;
    pointToPoint.SetDeviceAttribute ("DataRate", StringValue ((std::to_string(bandwidth)+"Mbps").c_str()));
    pointToPoint.SetChannelAttribute ("Delay", StringValue ((std::to_string(latency)+"ms").c_str()));

    NetDeviceContainer p2pDevices;
    p2pDevices = pointToPoint.Install (curNodes);

    Ipv4AddressHelper address;
    address.SetBase (("10."+std::to_string(i+1)+".0.0").c_str(), "255.255.0.0"); // Remember: 10.0.0.0 is used by WIFI
    Ipv4InterfaceContainer p2pInterfaces;
    p2pInterfaces = address.Assign (p2pDevices);

    if(i==nbHop-2){ // If we are on the last for loop (before last node)
      cloudIP=p2pInterfaces.GetAddress (1); // Get Last node interface
      PacketSinkHelper apSink("ns3::UdpSocketFactory",InetSocketAddress (Ipv4Address::GetAny (), cloudPort));
      ApplicationContainer sinkApp=apSink.Install(curNodes.Get(1)); // Instal sink on last node
      sinkApp.Get(0)->TraceConnect("Rx","CloudSwitch",MakeCallback(&PktReceived));
      sinkApp.Start (Seconds (0));
    }
  }

  return(std::make_pair(HopNodes,std::make_pair(cloudIP,cloudPort)));

}