# -*- coding: utf-8 -*-
import colorama
import os
from datetime import datetime


class Output(object):
    """ Manages the output, either to the stdout or the file. """

    def __init__(self, results: dict, no_colors: bool):
        self.results = results
        self.no_colors = no_colors

        if not no_colors:
            colorama.init()

        # Fix duplicates
        for name in self.results:
            self.results[name] = list(set(self.results[name]))

    def output_results(self):
        for name, values in self.results.items():
            if len(values) == 0:
                self.print_message("[-] Did not find %s" % name, False)

            self.print_message("Found %s at %s" % (
                name,
                ', '.join(hex(r) for r in values)
            ), True)

    def print_message(self, message: str, severity=None) -> None:
        if severity:
            prefix = "[+] "
            color_code = colorama.Fore.LIGHTGREEN_EX
        if severity == False:
            prefix = "[-] "
            color_code = colorama.Fore.LIGHTRED_EX
        if severity == None or self.no_colors:
            prefix = ""
            color_code = ""

        print(color_code + "%s%s" % (prefix, message) + colorama.Style.RESET_ALL)


    def save_results(self, config: dict, file: object):
        if len(self.results) == 0:
            return

        lines = []

        for name, values in self.results.items():
            # Do not output not-found results
            if len(values) == 0:
                continue

            for index, value in enumerate(values):
                line = config["pattern"]
                line = line.replace("{name}", name)
                line = line.replace("{value}", str(hex(value)))

                if index == 0 and len(values) > 1 and config["warn_on_mismatch"]:
                    line += " %s %s" % (config["comment_prefix"], "Warning: possible mismatch")
                if index > 0 and config["output_mismatch"]:
                    line = ("%s " % config["comment_prefix"]) + line

                lines.append(line)

        # Write to file
        file.write("%s Generated by straverse at %s\n" % (
            config["comment_prefix"],
            datetime.now().isoformat()
        ))
        for line in lines:
            file.write(line + '\n')
