﻿from PySide6.QtWidgets import QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton

from pypos.core.base_view import BaseView
from pypos.modules.auth.services.login_attempt_guard_service import LoginAttemptGuardService
from pypos.modules.auth.services.master_password_service import MasterPasswordService


class MasterPasswordDialog(BaseView, QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.service = MasterPasswordService()
        self.attempt_guard_service = LoginAttemptGuardService()
        self.setWindowTitle("Master Password")
        layout = QVBoxLayout(self)

        self.label = QLabel("Masukkan master password:")
        layout.addWidget(self.label)

        self.input = QLineEdit()
        self.input.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.input)

        self.button = QPushButton("OK")
        self.button.clicked.connect(self.verify_password)
        layout.addWidget(self.button)

        self.setLayout(layout)

    def verify_password(self):
        scope = LoginAttemptGuardService.SCOPE_MASTER_PASSWORD
        identity = "config_dialog_access"
        lock_state = self.attempt_guard_service.check_attempt(scope, identity)
        if lock_state.get("locked"):
            self.show_warning(
                "Terlalu Banyak Percobaan",
                self.attempt_guard_service.build_lock_message("master password", lock_state),
            )
            self.input.clear()
            self.input.setFocus()
            return

        entered = self.input.text()
        ok, reason = self.service.verify_with_reason(entered)
        if ok:
            self.attempt_guard_service.reset_attempt(scope, identity)
            self.accept()
            return

        failed_state = self.attempt_guard_service.record_failure(scope, identity)
        if failed_state.get("locked"):
            self.show_warning(
                "Terlalu Banyak Percobaan",
                self.attempt_guard_service.build_lock_message("master password", failed_state),
            )
            self.input.clear()
            self.input.setFocus()
            return
        if reason == "not_configured":
            self.show_error(
                # edited by glg
                # Strict mode semestinya selalu terkonfigurasi ke dev-only-secret.
                "Master password strict mode tidak aktif.\n"
                "Mode ini seharusnya selalu menggunakan `dev-only-secret`."
            )
            self.input.clear()
            self.input.setFocus()
            return
        self.show_warning("Gagal", "Master password salah")
        self.input.clear()
        self.input.setFocus()
