import flet as ft
from dbActions.users import Users
import re
import time

class Register:
    def __init__(self, page: ft.Page, auth, login):
        self.page = page
        self.auth = auth
        self.login = login
        self.users_manager = Users()
        self.email = ft.TextField(label="E-mail")
        self.password = ft.TextField(label="Parola", password=True, can_reveal_password=True)
        self.repeat_password = ft.TextField(label="Repeta parola", password=True, can_reveal_password=True)
        self.error_message = ft.Text("", color=ft.Colors.RED)

    def on_login_btn_click(self, e):
        self.auth.placeholder.content = self.login.build()
        self.auth.placeholder.update()

    def _is_valid_email(self, email: str) -> bool:
        email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        if re.fullmatch(email_regex, email) is not None:
            self.error_message.value = ""
            self.error_message.update()
            return True
        else: 
            self.error_message.value = "Va rugam inserati un e-mail valid!"
            self.error_message.update()
            return False
    
    def _are_all_fields_inserted(self, email=None, password=None, repeat_password=None):
        valid = True
        self.error_message.value = ''
        if not email:
            valid = False
        if not password:
            valid = False
        if not repeat_password:
            valid = False
        if not valid:
            self.error_message.value = "Toate campurile sunt obligatori!"
        self.error_message.update()
        return valid
    
    def _check_repeat_password(self, password, confirm_password):
        if password == confirm_password:
            self.error_message.value = ""
            self.error_message.update()
            return True
        else:
            self.error_message.value = "Parolele nu se potrivesc!"
            self.error_message.update()
            return False
        
    def _is_password_strong(self, password):
        self.error_message.value = ""
        if len(password) < 8:
            self.error_message.value = "Parola trebuie sa fie cel putin 8 caractere!"
            self.error_message.update()
            return False
        if not re.search(r"[A-Z]", password):
            self.error_message.value = "Parola trebuie sa contina cel putin o litera mare!"
            self.error_message.update()
            return False
        if not re.search(r"[a-z]", password):
            self.error_message.value = "Parola trebuie sa contina cel putin o litera mica!"
            self.error_message.update()
            return False
        if not re.search(r"[0-9]", password):
            self.error_message.value = "Parola trebuie sa contina cel putin un numar!"
            self.error_message.update()
            return False
        if not re.search(r"[^a-zA-Z0-9]", password):
            self.error_message.value = "Parola trebuie sa contina cel putin un caracter special (exp: !@#$%^&*)!"
            self.error_message.update()
            return False
        self.error_message.update()
        return True


    def on_register_btn_click(self, e):
        email = self.email.value
        password = self.password.value
        repeat_password = self.repeat_password.value
        if self._are_all_fields_inserted(email, password, repeat_password):
            print("All fileds are inserted")
            if self._is_valid_email(email):
                print("Email is valid")
                if self._is_password_strong(password):
                    print('Password is string')
                    if self._check_repeat_password(password, repeat_password):
                        print("Password is valid!")
                        password_hash = self.users_manager.hash_password(password)
                        if self.users_manager.register_user(email, password_hash):
                            self.error_message.value = "Inregistrarea a avut loc cu succes, va puteti autentifica!"
                            self.error_message.color = ft.Colors.GREEN
                            self.error_message.update()
                            time.sleep(3)
                            self.on_login_btn_click('')
                        else:
                            self.error_message.value = 'Exita deja un cont cu acet email. Daca ati fost invitat sau ati uitat prola accesati rubrica "Ai uitat parola?"'
                            self.error_message.update()

    def build(self):
        return ft.Column(
            [
                self.email,
                self.password,
                self.repeat_password,
                self.error_message,
                ft.Row(
                    [
                        ft.Button("Creaza cont", width=200, on_click=self.on_register_btn_click)
                    ],
                    alignment=ft.MainAxisAlignment.CENTER
                ),
                ft.Text(),
                ft.Row(
                    [
                        ft.TextButton("Inapoi la Autentificare", on_click=self.on_login_btn_click),
                    ],
                    alignment=ft.MainAxisAlignment.CENTER
                )
            ]
        )