import os
import msvcrt
import sys




class SubsectionManager:
    def __init__(self):
        self.subsections = []


    def add(self, size, names: list, functions: list, section: str, uppersection: str):
        self.subsections.append(
            Subsection(size, names, functions, section, uppersection)
        )



class Subsection:
    def __init__(self, size, names: list, functions: list, section: str, uppersection: str = ""):
        self.list = ["\x1b[30;47m"]
        self.names = names[::]
        self.uppersection = uppersection
        self.section = section
        self.functions = functions[::]


        for i in range(size - 1):
            self.list.append("")



class UserInterface:
    def __init__(self, size: int):
        self.list = ["\x1b[30;47m"]
        self.pointer = 0
        self._names = []
        self.functions = []
        self.subsection = SubsectionManager()
        self.path=[]


        for i in range(size - 1):
            self.list.append("")


    def setup(self, names: list, functions: list):
        if len(names) == 0 or len(functions) == 0 or len(names) != len(functions):
            raise ValueError("names and functions must be non-empty and of equal length")


        self._names = names[::]
        self.functions = functions[::]


    def _move_pointer(self, bgcolor, key, pointer=0):
        if key == b'w':
            if pointer - 1 < 0:
                return pointer
            bgcolor[pointer], bgcolor[pointer - 1] = bgcolor[pointer - 1], bgcolor[pointer]
            return pointer - 1


        if key == b's':
            if pointer + 1 > len(bgcolor) - 1:
                return pointer
            bgcolor[pointer], bgcolor[pointer + 1] = bgcolor[pointer + 1], bgcolor[pointer]
            return pointer + 1
        else:
            return pointer


    def begin(self, _list: list = None, _names: list = None, _functions: list = None,title:str="Home"):
        if _list is None:
            _list = self.list[::]
        if _names is None:
            _names = self._names
        if _functions is None:
            _functions = self.functions
        self.path.append(title)


        self.pointer = 0
        l = len(_list)


        _list = ["\x1b[30;47m"]
        for i in range(l - 1):
            _list.append("")
        steps = 0
        temp=0


        while True:
            try:
                os.system("cls")
                for i in self.path:
                    sys.stdout.write(f"/{i}")
                    sys.stdout.flush()

                print("\n")

                col,lines=os.get_terminal_size(1)
                if self.pointer>=lines//2 and self.pointer>temp:
                    steps+=1
                    temp=self.pointer
                elif self.pointer<temp:
                    steps-=1
                    temp=self.pointer
                if steps<0:
                    steps=0


                if len(_names)<lines-3:
                    steps=0
                for counter in range(steps,steps+(lines-4)):
                    if counter==len(_names):
                        break
                    print(f"{_list[counter]} {_names[counter]}\x1b[0m")


                key = msvcrt.getch()
                self.pointer = self._move_pointer(_list, key, self.pointer)


                if key == b'\r' and self.search_subsection(_names[self.pointer]):
                    next_section = self.search_subsection(_names[self.pointer])
                    print(self.pointer)


                    self.begin(next_section.list, next_section.names, next_section.functions,next_section.section)


                    self.pointer = 0
                    temp=0
                    steps=0
                    l = len(_list)
                    _list = ["\x1b[30;47m"]


                    for i in range(l - 1):
                        _list.append("")


                    continue


                if key == b'\r':
                    _functions[self.pointer]()


                if key == b'\x03':
                    quit()


                if key == b'\x1B':
                    del(self.path[-1::])
                    return

            except IndexError:
                print("index error")
                self.pointer = 0
                temp = 0
                steps = 0
                l = len(_list)
                _list = ["\x1b[30;47m"]
                for i in range(l - 1):
                    _list.append("")

    def search_subsection(self, names):
        for sub in self.subsection.subsections:
            if names == sub.section:
                return sub
        return False


    def add_sub_section(self, names:list, functions:list, section:str, uppersection:str=""):
        if len(names) - len(functions) != 0:
            raise ValueError("names and functions must be non-empty and of equal length")


        size = len(names)
        self.subsection.add(size, names, functions, section, uppersection)


        if uppersection != "":
            section_obj = self.search_subsection(uppersection)
            section_obj.names.append(section)
            section_obj.list.append("")
            section_obj.functions.append(None)
        else:
            self.list.append("")
            self._names.append(section)
            self.functions.append(None)



def progressbar(progress: int, width: int = 30):
        filled = int(width * progress / 100)
        bar = "█" * filled + "-" * (width - filled)
        sys.stdout.write(f"\r[{bar}] {progress}%")
        sys.stdout.flush()
def clear():
    os.system("cls")


def confirm(message:str):
    print(message+"(Y/N)")
    user_input=input("Enter:")
    if user_input=="y" or user_input=="Y":
        return True
    else:
        return False



