import numpy as np
import pandas as pd
import matplotlib.pyplot as plt



# A. Sum in Bytes and MB
def bytes_and_MBytes(df):
    print(df["Length"].sum() / 8, "Bytes")
    print(df["Length"].sum() / 1048576, "MB")


# B. find IPs that received pings and how much data they received 
def ping_target_ips(df):
    data_per_ip = {}

    destination_IPs = df["Destination"]
    lengths = df["Length"]
    protos = df["Protocol"]

    # iterate over all IPs
    for i in range(len(destination_IPs)):
        # check only for pings (ICMP) traffic
        if protos[i] != 'ICMP':
            continue

        # initialize entry in the directory for IP
        if destination_IPs[i] not in data_per_ip:
            data_per_ip[destination_IPs[i]] = 0

        # add the length of packet
        data_per_ip[destination_IPs[i]] += lengths[i]

    # print of IPs with corresponding data    
    for ip, data in data_per_ip.items():
        print(ip, '\t', data)
    

# C. plot pie chart
def pie_chart(df):
    protocols = df["Protocol"]
    packets_per_protocol = {}
    target_protocols = ['TCP', 'DNS', 'ARP', 'ICMP']


    # iterate over all entries
    for i in range(len(protocols)):
        # if the protocol is not one from the exercise, we skip it
        if protocols[i] not in target_protocols:
            continue

        # initialize entry in the directory for protocol
        if protocols[i] not in packets_per_protocol:
            packets_per_protocol[protocols[i]] = 0

        # increment packet count of protocol by 1
        packets_per_protocol[protocols[i]] += 1
    
    # we use the protocol names as labels, for the plot
    labels = list(packets_per_protocol.keys())
    # the values are the packet counts
    packets = list(packets_per_protocol.values())

    fig, ax = plt.subplots()
    # autopct option inserts the percentages
    ax.pie(packets, labels=labels, autopct='%1.1f%%')
    plt.show()


df = pd.read_csv("./capture.csv")
line = "\n========================================="

print(line)
bytes_and_MBytes(df)

print(line)
ping_target_ips(df)
pie_chart(df)