"""Konto: Tibia-Zugang sicher speichern (Windows-DPAPI).

Gleiche Speicherlogik wie vorher, als klare Karte mit Statusmeldung
inline statt Popup.
"""
import customtkinter

from src.security.credentials import load_credentials, save_credentials
from src.ui import theme
from src.ui.widgets import Card


class AccountPage(customtkinter.CTkFrame):
    def __init__(self, master):
        super().__init__(master, fg_color='transparent')
        self.grid_columnconfigure(0, weight=1)

        try:
            existing = load_credentials()
        except (OSError, ValueError):
            existing = None
        existing = existing or {'account': '', 'password': ''}
        self.existingPassword = existing['password']

        card = Card(self, 'Tibia-Account',
                    'Wird mit Windows-DPAPI verschluesselt gespeichert')
        card.grid(row=0, column=0, padx=0, pady=0, sticky='new')
        card.body.grid_columnconfigure(0, weight=1)

        customtkinter.CTkLabel(
            card.body, text='Account', font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=0, column=0, sticky='w', pady=(2, 2))
        self.account = customtkinter.CTkEntry(card.body, width=320)
        self.account.insert(0, existing['account'])
        self.account.grid(row=1, column=0, sticky='ew', pady=(0, 8))

        customtkinter.CTkLabel(
            card.body, text='Passwort', font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=2, column=0, sticky='w', pady=(2, 2))
        self.password = customtkinter.CTkEntry(
            card.body, width=320, show='•',
            placeholder_text='Leer = gespeichertes Passwort behalten',
        )
        self.password.grid(row=3, column=0, sticky='ew', pady=(0, 8))

        self.statusLabel = customtkinter.CTkLabel(
            card.body, text='', font=theme.font(11),
        )
        self.statusLabel.grid(row=4, column=0, sticky='w')

        customtkinter.CTkButton(
            card.body, text='Sicher speichern', height=38, corner_radius=10,
            font=theme.font(13, 'bold'), fg_color=theme.ACCENT,
            hover_color=theme.ACCENT_HOVER, command=self.save,
        ).grid(row=5, column=0, sticky='ew', pady=(6, 0))

    def save(self):
        password = self.password.get() or self.existingPassword
        try:
            save_credentials(self.account.get(), password)
        except (OSError, ValueError) as error:
            self.statusLabel.configure(
                text=str(error), text_color=theme.DANGER)
            return
        self.existingPassword = password
        self.password.delete(0, 'end')
        self.statusLabel.configure(
            text='Gespeichert (Windows-DPAPI).', text_color=theme.SUCCESS)
