import flet as ft
from dbActions.users import Users
from dbActions.company import Company

class ProfilePage:
    def __init__(self, page: ft.Page):
        self.page = page
        self.user_manager = Users()
        self.company_manager = Company()
        self.user = self.page.session.get("user")
        self.company = self.company_manager.get_company(self.user['id'])
        prenume = ''
        if "@default.com" not in self.user['email']:
            if self.user['name']:
                if '~' in self.user['name']:
                    prenume = self.user['name'].split('~')[0] 
        self.first_name = ft.TextField(
            label="Prenume",
            value=prenume
        )
        nume = ''
        if "@default.com" not in self.user['email']:
            if self.user['name']:
                if '~' in self.user['name']:
                    nume = self.user['name'].split('~')[1] 
        self.last_name = ft.TextField(
            label="Nume",
            value=nume
        )
        self.email = ft.TextField(label="E-mail", value=self.user['email'], read_only=True)
        self.phone = ft.TextField(label="Telefon", value=self.user['phone'] if self.user['phone'] else None)
        address = ''
        if self.user['address']:
            if "~" in self.user['address']:
                address = self.user['address'].split("~")[0].split("%")[1]
            else:
                address = self.user['address'].split("%")[1]
        self.address = ft.TextField(
            label="Strada si numar", 
            multiline=True, 
            min_lines=3, 
            max_lines=5, 
            value = address
        )
        city = ''
        if self.user['address']:
            if "~" in self.user['address']:
                city = self.user['address'].split("~")[0].split("%")[0]
            else:
                city = self.user['address'].split("%")[0]
        self.city = ft.TextField(
            label="Oras",
            value = city
        )
        self.company_name = ft.TextField(
            label="Denumire firma", 
            value=self.company['name'] if self.company else ''
        )
        self.vat = ft.TextField(
            label="CUI", 
            value=self.company['vat'] if self.company else ''
        )
        self.register_number = ft.TextField(
            label="Numar registru comert", 
            value=self.company['register_number'] if self.company else ''
        )
        self.company_address = ft.TextField(
            label="Sediu",  
            multiline=True, 
            min_lines=3, 
            max_lines=5,
            value=self.company['address'] if self.company else '')
        self.second_address_placeholder = ft.Column()
        self.second_address = ft.TextField(
                label="Adresa de livrare (str, nr, oras, judet)",
                multiline=True, 
                min_lines=3, 
                max_lines=5,
                value=self.user['address'].split("~")[1] if self.user['address'] and "~" in self.user['address'] and len(self.user['address'].split("~"))>1 else ''
            )
        self.second_address_placeholder =ft.Column()
        self.order_placeholder =ft.Column()
        self.error_message = ft.Text("", text_align=ft.TextAlign.CENTER)

        if self.user['address'] and len(self.user['address'].split("~"))>1 :
            self.is_second_address = True
            self.second_address_placeholder.controls.append(self.second_address)
        if self.company:
            self.is_company = True
            self.order_placeholder.controls.append(self.company_name)
            self.order_placeholder.controls.append(self.vat)
            self.order_placeholder.controls.append(self.register_number)
            self.order_placeholder.controls.append(self.company_address)

        self.is_company = False
        self.is_second_address = False

    def on_second_address_btn_click(self, e):
        self.is_second_address = True
        self.second_address_placeholder.controls.append(self.second_address)
        self.second_address_placeholder.update()

    def on_order_btn_click(self, e):
        self.is_company = True
        self.order_placeholder.controls.append(self.company_name)
        self.order_placeholder.controls.append(self.vat)
        self.order_placeholder.controls.append(self.register_number)
        self.order_placeholder.controls.append(self.company_address)
        self.order_placeholder.update()

    def check_inserted_user_data(self, username, phone, address, city):
        found = False
        if username is None or len(username)< 1:
            found = True
        if phone is None or len(phone)< 1:
            found = True
        if address is None or len(address)< 1:
            found = True
        if city is None or len(city)< 1:
            found = True
        if found: 
            self.error_message.value = "Toate campurile sunt obligatori!"
            self.error_message.color = ft.Colors.RED
            self.error_message.update()
        
        return found
    
    def check_second_address_inserted(self, address):
        if address is None or len(address)< 1:
            self.error_message.value = "Va rugam inserati adresa de livrare!"
            self.error_message.color = ft.Colors.RED
            self.error_message.update()
            return True
        return False
    
    def check_company_data_inserted(self, company_name, vat, register_number, company_address):
        found = False
        if company_name is None or len(company_name)< 1:
            found = True
        if vat is None or len(vat)< 1:
            found = True
        if register_number is None or len(register_number)< 1:
            found = True
        if company_address is None or len(company_address)< 1:
            found = True
        if found: 
            self.error_message.value = "Toate campurile sunt obligatori!"
            self.error_message.color = ft.Colors.RED
            self.error_message.update()
        return found

    def on_save_btn_click(self, e):
        username = self.first_name.value + "~" + self.last_name.value
        phone = self.phone.value
        address = self.city.value+"%"+self.address.value
        if self.is_second_address:
            if self.check_second_address_inserted(self.second_address.value):
                return
            address = self.city.value+"%"+self.address.value + '~' + self.second_address.value
        if self.check_inserted_user_data(username, phone, self.address.value, self.city.value): 
            return
        self.user_manager.update_user_data(username, phone, address, self.user['id'])

        if self.is_company:
            if self.check_company_data_inserted(self.company_name.value, self.vat.value, self.register_number.value, self.company_address.value):
                return
            if self.company:
                company['name'] = self.company_name.value
                company['vat'] = self.vat.value
                company['register_number'] = self.register_number.value
                company['address'] = self.company_address.value
                self.company_manager.update_company(company)
            else:
                company = {
                    'user_id' : self.user['id'],
                    'name': self.company_name.value,
                    'vat': self.vat.value,
                    'register_number': self.register_number.value,
                    'address': self.company_address.value
                }
                self.company_manager.add_company(company)
        
        self.error_message.value = "Profilul a fost salvat!"
        self.error_message.color = ft.Colors.GREEN
        self.error_message.update()
        self.user = self.user_manager.get(self.user['id'])
        self.page.session.set('user',self.user)
        self.first_name.value=self.user['name'].split('~')[0]
        self.first_name.update()
        self.last_name.value=self.user['name'].split('~')[1]
        self.last_name.update()
        self.phone.value = self.user['phone']
        self.phone.update()
        self.address.value = self.user['address'].split("~")[0].split("%")[1] if self.user['address'] else ''
        self.address.update()
        self.city.value = self.user['address'].split("~")[0].split("%")[0] if self.user['address'] else ''
        self.city.update()
        try:
            self.company = self.company_manager.get_company(self.user['id'])
            self.company_name.value=self.company['name'] if self.company else ''
            self.company_name.update()
            self.vat.value = self.company['vat'] if self.company else ''
            self.vat.update()
            self.register_number.value=self.company['register_number'] if self.company else ''
            self.register_number.update()
            self.company_address.value=self.company['address'] if self.company else ''
            self.company_address.update()
        except Exception as e:
            print ("Unable to save company data", e)
        try:
            self.second_address.value=self.user['address'].split("~")[1] if self.user['address'] and len(self.user['address'].split("~"))>1 else ''
            self.second_address.update()
        except Exception as e:
            print("Unable to save delivery address.", e)

    def on_back_btn_click(self, e):
        self.page.go('/')
    
    def on_logout_btn_click(self, e):
        self.page.session.clear()
        self.page.go('/')

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.FilledButton(
                                "Inapoi", 
                                icon=ft.Icons.ARROW_BACK,
                                on_click = self.on_back_btn_click
                            )
                        ], 
                        alignment=ft.MainAxisAlignment.END
                    ),
                    ft.Icon(name=ft.Icons.ACCOUNT_CIRCLE, size=100),
                    self.first_name,
                    self.last_name,
                    self.email,
                    self.phone,
                    self.address,
                    self.city,
                    ft.Divider(),
                    ft.Text("Adresa de livrare difera de adresa de domiciliu?", text_align=ft.TextAlign.CENTER),
                    ft.Button("Adauga adresa livrare", width=400, on_click=self.on_second_address_btn_click),
                    self.second_address_placeholder,
                    ft.Divider(), 
                    ft.Button("Doriti Factura?", width=400, on_click=self.on_order_btn_click),
                    self.order_placeholder,
                    self.error_message,
                    ft.FilledButton(
                        "Salveaza",
                        icon=ft.Icons.SAVE, 
                        on_click=self.on_save_btn_click, 
                        width=400
                    ),
                    ft.FilledButton(
                        "Deconectare", 
                        icon=ft.Icons.LOGOUT, 
                        on_click=self.on_logout_btn_click, 
                        width=400,
                        bgcolor=ft.Colors.GREY
                    ),
                    ft.Text("")
                ],
                width=400,
                alignment=ft.MainAxisAlignment.START,
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                scroll=ft.ScrollMode.ADAPTIVE
            ),
            padding=10,
            expand=True
        )