#!/usr/bin/env python3

from requests import get
from os.path import isfile
from re import compile, match


class MACChecker:
    def __init__(self):
        self._url = "https://standards-oui.ieee.org/oui/oui.txt"
        self._ouiTextFile = "oui.txt"

    def updateOUIDb(self):
        print("Updating the OUI database from IEEE")
        report = dict()

        # We download the data from IEEE
        oui = get(self._url)
        if oui.status_code != 200:
            report['success'] = False
            exit(1)
        
        with open(self._ouiTextFile, "w") as f:
            f.write(oui.text)

        report['success'] = True
        return report

    def parseMACAddress(self, mac):
        report = dict()
        report['hw'] = mac

        if ':' in mac:
            mac = mac.replace(":", "-")

        # Check if mac is valid
        regex = "[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}-[a-fA-F0-9]{2}"
        compiled = compile(regex)
        if not compiled.match(mac):
            print("Not a valid MAC address")
            return

        # Check if the oui.txt file exist
        if not isfile(self._ouiTextFile):
            report['db'] = self.updateOUIDb() 
        entries = self._parseOUIFile()

        macSplitted = mac.split("-")
        oui = macSplitted[0] + macSplitted[1] + macSplitted[2]
        oui = oui.upper()
        report['oui'] = oui

        f = self._parseOUIFile()
        for entries in f.keys():
            if oui == entries:
                report['vendor'] = f[entries][0]

        return report

    def _parseOUIFile(self):
        data = list()
        entries = dict()

        with open(self._ouiTextFile, "r") as f:
            data = f.readlines()

        # Remove the "header" on the file
        d = data[4:]
        regex = "[a-zA-Z0-9]{6}"
        compiled = compile(regex)
        for entry in d:
            s_entry = entry.split("\t")
            s = len(s_entry)
            if compiled.match(s_entry[0]):
                oui = s_entry[0].split(" ")
                entries[oui[0]] = s_entry[s - 1: s]

        return entries
