import hashlib
import hmac

from pypos.core.base_service import BaseService
from pypos.modules.auth.config.auth_config import get_master_password_hash


class MasterPasswordService(BaseService):
    def __init__(self):
        super().__init__()

    # edited by glg
    def is_configured(self):
        return bool(str(get_master_password_hash() or "").strip())

    # edited by glg
    def verify_with_reason(self, password):
        configured_hash = str(get_master_password_hash() or "").strip()
        if not configured_hash:
            return False, "not_configured"
        entered = str(password or "")
        entered_hash = hashlib.sha256(entered.encode()).hexdigest()
        # edited by glg
        # Bandingkan hash secara constant-time agar lebih tahan analisis timing.
        if hmac.compare_digest(entered_hash, configured_hash.lower()):
            return True, "ok"
        return False, "invalid"

    def verify(self, password):
        ok, _ = self.verify_with_reason(password)
        return ok
