from error_handler import MyError, ErrorScreen0
from menu import Menu
import os, time

class Trousseau0(Menu):
	def __init__(self, parent):
		super().__init__(parent)
		self.entrees = None
		self.selected = 0
		
	def loadPasswordList(self):
		try:
			# --- Open ---
			conf_file = open('config.txt', 'r') 
			line = conf_file.readline()
			# --- Read ---			
			while ( "password_directory=" not in line) and len(line)>0: #Lecture
				line = conf_file.readline()
			# --- Search option ---
			if not "password_directory=" in line : 
				raise MyError("Password_directory not found in config.txt")
			# --- Extract path value ---
			start = line.find("=") + 1
			if start == 0 : 
				raise MyError(" '=' not found in : " + line)
			end = line.find(";")
			if end == -1 :
				raise MyError(" ';' not found in : " + line)
			password_path = line[start:end]
			
			if not os.path.exists(password_path):
				raise MyError(password_path + " not found")
			
			pass_list = []
			for filename in os.listdir(password_path):
				pass_file = open(password_path+'/'+filename, 'r') 
				content = pass_file.readline()
				pass_list.append({'name': filename, 'submenu':
					Password(self, titre=filename, encrypted=content)}) 
		
			return pass_list	
		
		except Exception as e:
			print(e)
			return [{'name' : '0 mot de passe', 'submenu' : ErrorScreen0(self, e)}]
			
	def display(self, key, display):
		 # --- Loading Passwords ---
		if not self.entrees:
			self.entrees = self.loadPasswordList()
		
		# --- Rendering ---
		
		self.printList(display, self.selected, self.entrees)
		
		# --- User's Inputs ---
		return self.selectMenu(key, display)
				
class Password(Menu):
	def __init__(self, parent, titre=None, encrypted=None):
		super().__init__(parent)
		self.titre = titre
		self.encrypted = encrypted
		self.decrypted = None
		self.menu_unlock = Unlock0(self)
		self.menu_play = Play0(self)
		self.menu_modify = Modify0(self)
	
	def display(self, key, display):
		# --- User's Inputs ---
		if key == '0' : 
			display.clear()
			return self.parent
		
		# --- Rendering ---
		display.println(self.titre)
		display.println(self.encrypted)
		
		return self
		
class Unlock0(Menu):
	def __init__(self, parent):
		super().__init__(parent)
		
	def display(self, key, display):
		# --- User's Inputs ---
		display.clear()
		if key == '0' : 
			display.clear()
			return self.parent
		
		# --- Rendering ---
		display.println("Unlock0")
		
		return self
		
class Play0(Menu):
	def __init__(self, parent):
		super().__init__(parent)

	def display(self, key, display):
		# --- User's Inputs ---
		if key == '0' : 
			display.clear()
			return self.parent
		
		# --- Rendering ---
		display.println("Play0")
		
		return self
		
class Modify0(Menu):
	def __init__(self, parent):
		super().__init__(parent)

	def display(self, key, display):
		# --- User's Inputs ---
		if key == '0' : 
			display.clear()
			return self.parent
		
		# --- Rendering ---
		display.println("Modify0")
		
		return self
