import customtkinter

from src.ui import theme
from src.ui.widgets import FormModal, SearchableComboBox, positiveInt

BACKPACK_ITEMS = ['Orange Backpack', 'Red Backpack', 'Parcel']


class BuyBackpackModal(FormModal):
    """Backpack-Nachkauf beim NPC konfigurieren."""

    def __init__(self, parent, onConfirm=lambda: {}, waypoint=None):
        super().__init__(parent, 'Backpack kaufen')
        self.onConfirm = onConfirm
        options = waypoint['options'] if waypoint is not None else {}
        self.body.grid_columnconfigure(0, weight=1)

        customtkinter.CTkLabel(
            self.body, text='Item', font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=0, column=0, columnspan=2, sticky='w', pady=(4, 2))
        self.picker = SearchableComboBox(
            self.body, values=BACKPACK_ITEMS, placeholder='Item suchen …')
        self.picker.grid(row=1, column=0, columnspan=2, sticky='ew',
                         pady=(0, 4))
        self.picker.set(options.get('name', 'Orange Backpack'))

        customtkinter.CTkLabel(
            self.body, text='Menge', font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=2, column=0, columnspan=2, sticky='w', pady=(4, 2))
        self.amountEntry = customtkinter.CTkEntry(
            self.body, placeholder_text='z. B. 12', validate='key',
            validatecommand=(self.register(positiveInt), '%P'),
        )
        self.amountEntry.grid(row=3, column=0, columnspan=2, sticky='ew',
                              pady=(0, 6))
        self.amountEntry.insert(0, str(options.get('amount', 12)))

    def confirm(self):
        if self.picker.get() not in BACKPACK_ITEMS:
            return self.fail('Item aus der Liste waehlen.')
        amount = self.amountEntry.get()
        if not positiveInt(amount) or amount == '':
            return self.fail('Menge groesser als 0 angeben.')
        self.onConfirm(None, {
            'name': self.picker.get(),
            'amount': int(amount),
        })
        self.destroy()
