#!/bin/env python3
from __future__ import print_function
import re
import os
import sys
from pprint import pprint

PEER = re.compile(r'[0-9]+(?:\.[0-9]+){3}')

def main():
    filename = sys.argv[1]
    files = []
    if os.path.exists(os.path.abspath(filename)):
        files.append(filename)
    elif filename == '--all':
        files = list(filter(lambda x: x.endswith(".log"), os.listdir('.')))

    for f in files:
        print(f)
        with open(f, 'rb') as log_file:
            calculate_fairness(log_file)

def calculate_fairness(log_file):
    peers = {}
    for line in filter(is_piece_line, log_file.readlines()):
        peer = get_peer(line)
        if peers.get(peer) is None:
            peers[peer] = {'sent': 0, 'recv': 0}

        if is_recv_line(line):
            peers[peer]['recv'] += 1
        elif is_send_line(line):
            peers[peer]['sent'] += 1

    pprint(translate_peers(peers))

def translate_peers(ips):
    if not os.path.exists('./ips.txt'):
        return ips

    mappings = {}
    with open('./ips.txt', 'rb') as ip_file:
        for line in ip_file.readlines():
            ip, name = line.split('-')
            mappings[ip.strip()] = name.strip()

    new_peer_dict = {}
    for peer, send_recv in ips.items():
        matched_peer = mappings.get(peer, peer)
        new_peer_dict[matched_peer] = send_recv
    return new_peer_dict

def is_piece_line(line):
    return "BT_PIECE" in line

def is_recv_line(line):
    return "Received" in line

def is_send_line(line):
    return "Sent" in line

def get_peer(line):
    pattern = PEER.search(line)
    return pattern.group() if pattern is not None else None

if __name__ == '__main__':
    main()
