#!/usr/bin/env python3
import atexit
import os
import sys
import traceback

from get_msg import match_msg

try:
    from colorama import init
    from termcolor import colored

    # use Colorama to make Termcolor work on Windows too
    init()
except ImportError as error:
    print("could not import colorama:")
    print(error)
    exit(1)


# Collect the parameters
commit_msg_filepath = sys.argv[1]
if len(sys.argv) > 2:
    commit_type = sys.argv[2]
else:
    commit_type = ""
if len(sys.argv) > 3:
    commit_hash = sys.argv[3]
else:
    commit_hash = ""

# print('commit-msg: File: {}\nType: {}\nHash: {}'.format(
#    commit_msg_filepath,
#    commit_type,
#    commit_hash,
# ))


def clean_all(commit_msg_filepath: str = "./.git/COMMIT_EDITMSG"):
    # print('Registered cleanAll with {}'.format(commit_msg_filepath))

    filename = os.path.expanduser(commit_msg_filepath)

    if os.path.exists(filename):
        os.remove(commit_msg_filepath)
        print(colored("File {} removed!".format(commit_msg_filepath), "yellow"))


atexit.register(clean_all, commit_msg_filepath)


def podmena(commit_msg_filepath, enable=False):
    if enable:
        curdir = os.path.dirname(os.path.realpath(__file__))
        with open(os.path.join(curdir, "database.txt")) as f:
            emoji = f.readlines()

        with open(commit_msg_filepath) as f:
            text = f.read()

        with open(commit_msg_filepath, "w") as f:
            # f.write('{} :{}:'.format(text.strip(), random.choice(emoji).strip()))
            f.write("{} :{}:".format(text.strip(), os.urandom(emoji).strip()))


try:
    with open(commit_msg_filepath) as f:
        required_message = match_msg(commit_msg_filepath, commit_type)

        content = f.read()
        if not content.startswith(required_message):
            print(
                colored(
                    "commit-msg: ERROR! The commit message must start with {}".format(
                        required_message,
                    ),
                    "red",
                ),
            )
            sys.exit(1)

    # podmena(commit_msg_filepath=commit_msg_filepath, enable=True)

    os._exit(0)

except:  # noqa: ignore=E722
    traceback.print_exc()
    print(colored("Oops! COMMIT is failing. Switch to manual...", "red"))
    clean_all(commit_msg_filepath)
    sys.exit(2)
