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):
        self.tags = self._format_tags(service.tags)
        self.file_size = self._format_file_size(service.file_size)
        self.file_type = self._format_file_type(service.file_type)
        self.hashes = self._format_other_hashes(service.hashes)

    def _format_reputation(self, reputation: int) -> str:

        if reputation < 0:
            reputation_string = colored(str(reputation), "red")
        elif reputation > 0:
            reputation_string = colored(str(reputation), "green")
        else:
            reputation_string = colored(str(reputation), "yellow")

        return reputation_string

    def _format_detections(self, detections, detection_coverage, detection_count):

        detection_percent = detection_coverage * 100

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

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

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

        for detection, result in 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")

    def _format_tags(self, tags):
        return ", ".join(tags) if tags else None

    def _format_file_size(self, file_size):
        return size(file_size)

    def _format_file_type(self, file_type):
        return f".{file_type}"

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

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

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