#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/netanim-module.h"
#include "ns3/network-module.h"
#include "ns3/wifi-module.h"

#include <filesystem>
#include <iomanip>
#include <iostream>
#include <string>

using namespace ns3;

struct Pair {
    Ptr<Node> ap;
    Ptr<Node> client;
    NetDeviceContainer devices;
};
Pair BuildPair(Ptr<YansWifiChannel> channel, const std::string& apName,
               const std::string& clientName, double ax, double ay, double cx, double cy, uint16_t channelNumber = 36) {
    NodeContainer nodes;
    nodes.Create(2);
    MobilityHelper mobility;
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
    mobility.Install(nodes);
    nodes.Get(0)->GetObject<MobilityModel>()->SetPosition(Vector(ax,ay,0));
    nodes.Get(1)->GetObject<MobilityModel>()->SetPosition(Vector(cx,cy,0));
    YansWifiPhyHelper phy;
    phy.SetChannel(channel);
    phy.Set("ChannelSettings", StringValue("{"+std::to_string(channelNumber)+", 20, BAND_5GHZ, 0}"));
    WifiHelper wifi;
    wifi.SetStandard(WIFI_STANDARD_80211a);
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                 "DataMode", StringValue("OfdmRate24Mbps"),
                                 "ControlMode", StringValue("OfdmRate6Mbps"));
    WifiMacHelper mac;
    mac.SetType("ns3::ApWifiMac", "Ssid", SsidValue(Ssid(apName)));
    auto devices = wifi.Install(phy, mac, nodes.Get(0));
    mac.SetType("ns3::StaWifiMac", "Ssid", SsidValue(Ssid(clientName)),
                "ActiveProbing", BooleanValue(false));
    devices.Add(wifi.Install(phy, mac, nodes.Get(1)));
    return {nodes.Get(0),nodes.Get(1),devices};
}

int main(int argc, char* argv[]) {
    std::string scenario = "08A";
    std::string state = "before";
    CommandLine cmd(__FILE__);
    cmd.AddValue("case", "08A SSID, 08B range, or 08C co-channel contention", scenario);
    cmd.AddValue("state", "before or after", state);
    cmd.Parse(argc,argv);
    if ((scenario!="08A" && scenario!="08B" && scenario!="08C") ||
        (state!="before" && state!="after")) {
        std::cerr << "Use --case=08A|08B|08C and --state=before|after\n";
        return 2;
    }
    const bool before = state=="before";
    const std::string prefix = scenario+"-"+state;
    const bool coChannel = scenario=="08C";
    RngSeedManager::SetSeed(45);
    RngSeedManager::SetRun(2);
    auto channelFactory = YansWifiChannelHelper::Default();
    auto firstChannel = channelFactory.Create();
    std::string clientSsid = (scenario=="08A" && before) ? "WRONG-WIFI" : "LAB-WIFI";
    auto main = BuildPair(firstChannel,"LAB-WIFI",clientSsid,0,0,
                          (scenario=="08B" && before) ? 1400 : 8, 0);
    InternetStackHelper stack;
    stack.Install(NodeContainer(main.ap,main.client));
    Ipv4AddressHelper address;
    address.SetBase("192.168.10.0","255.255.255.0");
    auto mainIp = address.Assign(main.devices);
    uint32_t planned = coChannel ? 1600 : 300;
    const uint16_t port = 4801;
    UdpServerHelper server(port);
    auto mainServer = server.Install(main.ap);
    mainServer.Start(Seconds(0));
    UdpClientHelper client(mainIp.GetAddress(0),port);
    client.SetAttribute("MaxPackets", UintegerValue(planned));
    client.SetAttribute("Interval", TimeValue(coChannel ? MicroSeconds(450) : MilliSeconds(4)));
    client.SetAttribute("PacketSize", UintegerValue(1100));
    auto mainClient = client.Install(main.client);
    mainClient.Start(Seconds(1.1));

    Ptr<Node> otherAp;
    Ptr<Node> otherClient;
    if (coChannel) {
        auto other = BuildPair(before ? firstChannel : channelFactory.Create(),
                               "BACKGROUND","BACKGROUND",1,4,8,4,before ? 36 : 149);
        otherAp = other.ap;
        otherClient = other.client;
        stack.Install(NodeContainer(other.ap,other.client));
        address.SetBase("192.168.20.0","255.255.255.0");
        auto otherIp = address.Assign(other.devices);
        auto receiver = server.Install(other.ap);
        receiver.Start(Seconds(0));
        UdpClientHelper burst(otherIp.GetAddress(0),port);
        burst.SetAttribute("MaxPackets", UintegerValue(9500));
        burst.SetAttribute("Interval", TimeValue(MicroSeconds(170)));
        burst.SetAttribute("PacketSize", UintegerValue(1300));
        auto app = burst.Install(other.client);
        app.Start(Seconds(1.0));
    }
    YansWifiPhyHelper trace;
    trace.SetPcapDataLinkType(WifiPhyHelper::DLT_IEEE802_11_RADIO);
    trace.EnablePcap(prefix+"-station.pcap",main.devices.Get(1),false,true);
    AnimationInterface anim(prefix+".xml");
    anim.UpdateNodeDescription(main.ap,"Lab AP");
    anim.UpdateNodeDescription(main.client,"Lab station");
    if (coChannel) {
        anim.UpdateNodeDescription(otherAp,"Background AP");
        anim.UpdateNodeDescription(otherClient,"Background station");
    }
    anim.SetMaxPktsPerTraceFile(100000);
    Simulator::Stop(Seconds(coChannel ? 2.6 : 3.3));
    Simulator::Run();
    const auto delivered = DynamicCast<UdpServer>(mainServer.Get(0))->GetReceived();
    std::cout << prefix << " planned=" << planned << " delivered=" << delivered
              << " delivery_percent=" << std::fixed << std::setprecision(2)
              << (100.0 * delivered / planned) << '\n';
    Simulator::Destroy();
    const std::string capture = prefix+"-station.pcap";
    if (!std::filesystem::exists(capture)) {
        PcapHelper pcap;
        pcap.CreateFile(capture, std::ios::out, PcapHelper::DLT_IEEE802_11_RADIO);
    }
}
