import sys
import os
from PyQt5.QtWidgets import QApplication
from gui.main_window import MainWindow
from gui.login_dialog import LoginDialog
from gui.register_dialog import RegisterDialog

def main():
    # Create necessary directories
    os.makedirs('data', exist_ok=True)
    os.makedirs('models', exist_ok=True)

    app = QApplication(sys.argv)
    
    # Show login and main window with logout loop support
    def show_next_window():
        # Tampilkan login dialog terlebih dahulu
        show_login = True
        while True:
            if show_login:
                login_dialog = LoginDialog()
                result = login_dialog.exec_()
                
                # Cek apakah user ingin ke halaman register
                if login_dialog.should_show_register:
                    show_login = False  # Tampilkan register dialog next
                    continue
                
                # Cek apakah login berhasil
                if result == LoginDialog.Accepted and login_dialog.login_success:
                    # Create and show main window
                    window = MainWindow(login_dialog.username or "Admin")
                    
                    # Connect logout signal to show login again
                    window.logout_signal.connect(show_next_window)
                    
                    window.show()
                    break
                else:
                    # Login canceled, quit application
                    app.quit()
                    break
            else:
                # Tampilkan register dialog
                register_dialog = RegisterDialog()
                result = register_dialog.exec_()
                
                # Cek apakah user ingin kembali ke login
                if register_dialog.should_show_login:
                    show_login = True  # Kembali ke login
                    continue
                
                # Cek apakah register berhasil
                if result == RegisterDialog.Accepted and register_dialog.register_success:
                    # Setelah register berhasil, kembali ke login
                    show_login = True
                    continue
                else:
                    # Register canceled, quit application
                    app.quit()
                    break
    
    # Start the application by showing login dialog
    show_next_window()
    
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()