import auth
import file_widgets
import httpx
import keyring
import request_client
import sync
from PyQt6.QtWidgets import QMainWindow, QStackedWidget


class State(QMainWindow):
    def __init__(self, url: str):
        super().__init__()

        self.setWindowTitle("Auth App")

        self.stack = QStackedWidget()
        self.client = httpx.Client(base_url=url)
        self.register_widget = auth.RegisterWidget(self)
        self.login_widget = auth.LoginWidget(self)

        self.stack.addWidget(
            self.login_widget
        )  # Login widget is the first in the stack
        self.stack.addWidget(self.register_widget)

        self.setCentralWidget(self.stack)

        password = keyring.get_credential("auth_app", "access_token")
        if password is None:
            self.switch_to_login()  # Start with the login widget
        else:
            self.login(password.password)

    def switch_to_login(self):
        self.stack.setCurrentWidget(self.login_widget)

    def switch_to_register(self):
        self.stack.setCurrentWidget(self.register_widget)

    def login(self, token: str):
        keyring.set_password("auth_app", "access_token", token)
        request_client.RequestClient().set_token(token)
        sync.SyncData.sync_all(
            # "/home/stnicolay/backups",
            # uuid.UUID("0191397f-ae77-7b2a-bed7-9d28ed56a90a"),
        )
        self.file_widget = file_widgets.MainFileWidget(self)
        self.stack.addWidget(self.file_widget)
        self.stack.setCurrentWidget(self.file_widget)

    def logout(self):
        keyring.delete_password("auth_app", "access_token")
        request_client.RequestClient().delete_token()
        self.switch_to_login()
