from time import sleep

import pandas as pd

from mac.api_vendors import MacVendors


class Vendors:
    """Class obter vendor"""

    def __init__(self):
        self.response = {}
        self.output = {}

    def get_by_tuple(self, *args):
        """Get the information through a tuple"""

        for mac in args:

            if len(mac) >= 8:

                response = MacVendors(mac)
                tmp = {mac: response.vendor}
                self.response.update(tmp)

                sleep(0.5)

        if len(self.response) == 0:
            error = {'error': 'Need more than one item in the tuple, if you want to query only one prefix use the get_by_single method'}  # noqa:E501
            self.response.update(error)

    def get_by_file(self, file):
        """Get the information through a file"""

        with open(file, 'r', encoding='utf8') as macs:

            for mac in macs.readlines():
                vendor = MacVendors(mac.rstrip())
                tmp = {mac.rstrip(): vendor.vendor}
                self.response.update(tmp)

                sleep(0.5)

    def get_by_single(self, mac):
        """Get information from a single mac"""

        response = MacVendors(mac)
        tmp = {mac: response.vendor}
        self.response.update(tmp)

    def to_excel(self, path, file_name='mac-vendors'):
        """Get output to excel"""

        self.format_dict_export()

        df = pd.DataFrame(self.output)

        df.to_excel(
            path+'/'+file_name+'.xlsx',
            sheet_name=file_name,
            engine='xlsxwriter',
            index=False
        )

    def to_csv(self, path, file_name='mac-vendors'):
        """Get output to excel"""

        self.format_dict_export()

        df = pd.DataFrame(self.output)

        df.to_csv(
            path+'/'+file_name+'.csv',
            sep=';',
            index=False
        )

    def to_txt(self, path, file_name='mac-vendors'):
        """Get output to txt"""

        with open(
            f"{path}/{file_name}.txt",
            'w',
            encoding='utf8'
        ) as file:

            for mac, value in self.response.items():
                file.write(mac+"\t"+value+"\n")

    def format_dict_export(self):
        """Dictionary format to export"""

        macs = []
        vendors = []

        for mac, value in self.response.items():
            macs.append(mac)
            vendors.append(value)

        self.output["Mac"] = macs
        self.output["Vendor"] = vendors
