import os
from structures import Data_Structures as ds

class User():

    def __init__(self):
        self.username = None
        self.password = None
        self.saved = None

    def get_users(self):
        info = "users/login.dat"
        with open(info, 'rb') as file:
            username, usernames = "", []
            byte = file.read(1)
            while byte != b'':
                if byte == b'\x00':
                    usernames.append(username)
                    username = ""
                else:
                    username += byte.decode()
                byte = file.read(1)

        return usernames

    def new_user(self, username, password):
        self.username, self.password = username, password
        info = "users/login.dat"
        usernames = self.get_users()
        usernames.append(username)

        with open(info, 'wb') as file:
            for user in usernames:
                for char in user:
                    file.write(char.encode())
                file.write(b'\x00')

        user_path = "users/" + username
        os.mkdir(user_path)

        user_save = user_path + "/structures"
        os.mkdir(user_save)

        pass_path = user_path + "/" + "password.dat"
        with open(pass_path, 'wb') as file:
            for char in password:
                file.write(char.encode())

        with open(user_path+"/saved.txt", 'w') as file:
            file.write("")

    def change_pass(self, new_password):
        user_path = "users/" + self.username
        pass_path = user_path + "/" + "password.dat"

        with open(pass_path, 'wb') as file:
            for char in new_password:
                file.write(char.encode())

    def get_password(self):
        user_path = "users/" + self.username
        pass_path = user_path + "/" + "password.dat"

        with open(pass_path, 'rb') as file:
            password, byte = "", file.read(1)
            while byte != b'':
                password += byte.decode()
                byte = file.read(1)

        return password

    def save_structure(self, type, structure, name):
        file_path = "users/" + self.username + "/structures/" + name + ".dat"

        with open(file_path, 'wb') as file:
            if (type == "Stack"):
                file.write("S".encode())
                for data in structure:
                    for char in data:
                        file.write(char.encode())
                    file.write(b'\x00')

            if (type == "LinkedList"):
                file.write("L".encode())
                for data in structure:
                    for char in data:
                        file.write(char.encode())
                    file.write(b'\x00')

            if (type == "Tree"):
                tree : ds.Binary_Tree = structure
                nodes = tree.write_tree_to_file()
                if ('::' in nodes):
                    nodes = nodes.replace("::", ":T:")

                with open(file_path, 'wb') as file:
                    file.write("T".encode())
                    for node in nodes.split('\n'):
                        for char in node:
                            if (char == ":"):
                                file.write(b'\x00')
                            else:
                                file.write(char.encode())
                        file.write(b'\x00')
                        file.write(b'\x00')

                print("hotovo")

        structures = self.get_structures()
        structures.append(type + " : " + name)
        file_path = "users/" + self.username + "/saved.txt"

        with open(file_path, 'w') as file:
            for name in structures:
                file.write(name + '\n')

    def load_structure(self, file_name):
        # file_path = "users/" + self.username + "/" + file_name + ".dat"
        file_path = file_name
        with open (file_path, 'rb') as file:
            type = file.read(1).decode()
            byte = file.read(1)

            #STACK/LINKED LIST
            if (type == 'S' or type == 'L'):
                structure = []
                curr = ""
                while byte != b'':
                    if (byte == b'\x00'):
                        structure.append(curr)
                        curr = ""
                    else:
                        curr += byte.decode()
                    byte = file.read(1)

            #BINARY TREE
            if (type == 'T'):
                structure = ds.Binary_Tree()
                lines, line = "", ""
                nulbyte = False

                while (byte != b''):
                    if (byte == b'\x00'):
                        if (not nulbyte):
                            line += ":"
                            nulbyte = True
                        else:
                            lines += line + '\n'
                            line = ""
                    else:
                        line += byte.decode()
                        nulbyte = False

                    byte = file.read(1)

                for lin in lines.split('\n'):
                    if (lin != ''):
                        structure.add_node(lin)

            return (type, structure)

    def get_structures(self):
        file_path = "users/" + self.username + "/saved.txt"
        names = []

        with open(file_path, 'r') as file:
            for line in file:
                names.append(line)

        return names