import re
from collections import defaultdict
import matplotlib.pyplot as plt

def parse_file(file_path):
    with open(file_path, 'r') as file:
        data = file.read()

    pattern = re.compile(r'Source address: /(\d+\.\d+\.\d+\.\d+).*?Destination address: /(\d+\.\d+\.\d+\.\d+).*?Source port: (\d+).*?Destination port: (\d+)', re.DOTALL)
    matches = pattern.findall(data)

    return matches

def count_occurrences(matches):
    counts = defaultdict(int)
    src_ip_counts = defaultdict(int)
    dst_ip_counts = defaultdict(int)
    src_port_counts = defaultdict(int)
    dst_port_counts = defaultdict(int)

    for src_ip, dst_ip, src_port, dst_port in matches:
        counts[(src_ip, dst_ip, dst_port)] += 1
        src_ip_counts[src_ip] += 1
        dst_ip_counts[dst_ip] += 1
        src_port_counts[src_port] += 1
        dst_port_counts[dst_port] += 1

    return counts, src_ip_counts, dst_ip_counts, src_port_counts, dst_port_counts

def plot_data(counts):
    src_ips = []
    dst_ips = []
    ports = []
    occurrences = []

    for (src_ip, dst_ip, port), count in counts.items():
        src_ips.append(src_ip)
        dst_ips.append(dst_ip)
        ports.append(port)
        occurrences.append(count)

    fig, ax = plt.subplots(figsize=(10, 8))

    bar_width = 0.35
    index = range(len(src_ips))

    bars = ax.bar(index, occurrences, bar_width, label='Occurrences')

    ax.set_xlabel('IP and Port Combinations')
    ax.set_ylabel('Occurrences')
    ax.set_title('Occurrences of Source IPs, Destination IPs, and Ports')
    ax.set_xticks(index)
    ax.set_xticklabels([f'{src_ips[i]} -> {dst_ips[i]}:{ports[i]}' for i in range(len(src_ips))], rotation=90)
    ax.legend()

    plt.tight_layout()
    plt.show()

def plot_single_category(data, category_name):
    items = list(data.keys())
    occurrences = list(data.values())

    fig, ax = plt.subplots(figsize=(10, 8))

    bar_width = 0.35
    index = range(len(items))

    bars = ax.bar(index, occurrences, bar_width, label='Occurrences')

    ax.set_xlabel(category_name)
    ax.set_ylabel('Occurrences')
    ax.set_title(f'Occurrences of {category_name}')
    ax.set_xticks(index)
    ax.set_xticklabels(items, rotation=90)
    ax.legend()

    plt.tight_layout()
    plt.show()

# File path to your text file
file_path = 'sample.txt'

matches = parse_file(file_path)
counts, src_ip_counts, dst_ip_counts, src_port_counts, dst_port_counts = count_occurrences(matches)

# Plot each category
plot_data(counts)                      # Current graph with everything
plot_single_category(dst_ip_counts, 'Destination IPs')
plot_single_category(src_ip_counts, 'Source IPs')
plot_single_category(dst_port_counts, 'Destination Ports')
plot_single_category(src_port_counts, 'Source Ports')