import logging

from hurry.filesize import size
from tabulate import tabulate
from termcolor import colored

from ioccheck.cli.formatters import Formatter
from ioccheck.services import MalwareBazaar

logger = logging.getLogger(__name__)

f_handler = logging.FileHandler("ioccheck.log")
f_handler.setLevel(logging.INFO)

f_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
f_handler.setFormatter(f_format)

logger.addHandler(f_handler)


class MalwareBazaarFormatter(Formatter):
    def __init__(self, service: MalwareBazaar):
        Formatter.__init__(self, service)

    @property
    def detections(self):

        detection_percent = self.service.detection_coverage * 100

        detection_count_string = f"{self.service.detection_count} engines ({detection_percent:.2g}%) detected this file.\n"

        if self.service.detection_count == 0:
            detection_count_string = colored(detection_count_string, "green")
        elif self.service.detection_count > 0:
            detection_count_string = colored(detection_count_string, "red")

        table = [["Antivirus", "Detected", "Result"]]

        for detection, result in self.service.detections.items():
            if result.get("category") == "malicious":
                malicious = colored("Yes", "red")
            else:
                malicious = colored("No", "green")

            table.append([detection, malicious, result.get("result")])

        return tabulate(table, headers="firstrow", tablefmt="fancy_grid")

    @property
    def tags(self):
        return ", ".join(self.servicetags) if self.service.tags else None

    @property
    def file_size(self):
        return size(self.service.file_size)

    @property
    def file_type(self):
        return f".{self.service.file_type}"

    @property
    def hashes(self):
        results = [[k, v] for k, v in self.service.hashes.items() if v]

        table = [["Type", "Hash"]]
        [table.append(result) for result in results]

        return tabulate(table, headers="firstrow", tablefmt="fancy_grid")
