from colorama import Fore, Back, Style
import re


class UserInput:
    def __init__(
        self,
        dependencies: bool = False,
        build_system: bool = False,
        author: bool = False,
        repo: str = None,
    ) -> None:
        self.dependency_state = dependencies
        self.build_system_state = build_system
        self.author_state = author
        self.repo = repo
        self.license_options = {"1": "MIT", "2": "YUP"}
        self.os_options = {"1": "OS Independent", "2": "Linux"}
        self.build_system_options = {"1": "Hatchling"}
        self.authors = []
        self.dependencies = []
        # self.inputs = {}

    def run(self):
        # self.inputs = {"projectName": self._single_option("Module Name", None)}
        self.moduleName = self._normalize(self._single_option("Module Name", None))
        self.moduleVersion = self._single_option("Module Version", "0.0.1")

        if self.author_state:
            self.numberOfAuthors = self._single_option("Number of Authors", "1")
            self._get_authors(self.numberOfAuthors)
        else:
            self.authors.append(
                {"name": "Travis Baars", "email": "travis@trainland.io"}
            )

        self.description = self._single_option("Description", None)
        self.readme = self._single_option("Readme", "README.md")
        self.requiredPythonVersion = self._single_option(
            "Required Python Version", ">=3.7"
        )

        if self.dependency_state:
            self.rawDependencies = self._single_option("Dependencies", "none")
            self._get_dependencies(self.rawDependencies)
        else:
            pass
        self.license = self._multi_option(self.license_options, "1")
        self.operatingSystem = self._multi_option(self.os_options, "1")

        if self.repo:
            self.homepage = None
            self.bugTracker = None
        else:
            self.homepage = self._single_option("Homepage", None)
            self.bugTracker = self._single_option("Bug Tracker", None)

        if self.build_system_state:
            self.build_system = self._multi_option("Build System", "1")
        else:
            self.build_system = "hatchling"

        self.inputs = {
            "Module Name": self.moduleName,
            "Module Version": self.moduleVersion,
            "Authors": self.authors,
            "Description": self.description,
            "Readme": self.readme,
            "Required Python Version": self.requiredPythonVersion,
            "Dependencies": self.dependencies,
            "License": self.license,
            "Operating System": self.operatingSystem,
            "Homepage": self.homepage,
            "Bug Tracker": self.bugTracker,
            "Build System": self.build_system,
        }

        return self.inputs

    def _normalize(self, x):
        normal = x.lower().replace(" ", "_")
        return normal

    def _get_authors(self, num):
        for count in range(int(num)):
            name = self._single_option(f"  Name  {count + 1}", None)
            email = self._single_option(f"  Email {count + 1}", None)

            self.authors.append({"name": name, "email": email})

        return None

    def _get_dependencies(self, raw):
        if raw == "none":
            return None
        split = raw.split(" ")

        for dep in split:
            fix = dep.replace("=", " == ")

            self.dependencies.append(fix)

        return None

    def _single_option(self, option, default):
        count = 0
        while True:
            if count == 3:
                raise ValueError("no valid input detected")
            if not default == None:
                text = (
                    f"{option}:"
                    + Style.DIM
                    + f"[default = {default}] "
                    + Style.RESET_ALL
                )
                choice = input(text)
                if choice == "":
                    return default
                else:
                    return choice
            else:
                text = f"{option}: "
                choice = input(text)

            if choice:
                # self.inputs[option] = choice
                return choice
            else:
                #     # catch = re.sub(r"[ 0-9]", "", option)
                print(Fore.RED + f"please provide an input" + Fore.RESET)
                # print("please provide an input")
                count += 1
                # raise Exception("please provide an input")

    def _multi_option(solf, options: dict, default: str):
        if not default:
            raise ValueError("must set a default value")
        while True:
            print("Select an option:")
            for key, value in options.items():
                print(f"{key}: {value}")
            choice = input(
                "Enter the number of your choice:"
                + Style.DIM
                + "[default = 1] "
                + Style.RESET_ALL
            )

            if choice in options:
                return options[choice]
            elif choice == "":
                return options[default]
            else:
                print(Fore.RED + "Invalid choice. Please try again." + Fore.RESET)


# _collect = _UserInput()


# def get_user_input():
#     return _collect._run()


if __name__ == "__main__":
    # print(get_user_input())

    _collect = UserInput()

    # get_user_input()
