import customtkinter

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


class RefillCheckerModal(FormModal):
    """Pruefpunkt: ab welchen Mindestbestaenden zum Label springen."""

    def __init__(self, parent, onConfirm=lambda: {}, waypoint=None,
                 waypointsLabels=[]):
        super().__init__(parent, 'Refill-Checker')
        self.onConfirm = onConfirm
        options = waypoint['options'] if waypoint is not None else {}

        self.healthSwitch = customtkinter.CTkSwitch(
            self.body, text='Health pruefen', progress_color=theme.ACCENT,
            font=theme.font(12),
        )
        self.healthSwitch.grid(row=0, column=0, columnspan=2, sticky='w',
                               pady=(4, 3))
        if options.get('healthEnabled'):
            self.healthSwitch.select()

        self.healthEntry = self._amountRow(
            1, 'Min. Health Potions',
            options.get('minimumAmountOfHealthPotions'))
        self.manaEntry = self._amountRow(
            3, 'Min. Mana Potions', options.get('minimumAmountOfManaPotions'))
        self.capEntry = self._amountRow(
            5, 'Min. Cap', options.get('minimumAmountOfCap'))

        customtkinter.CTkLabel(
            self.body, text='Zum Label springen', font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=7, column=0, columnspan=2, sticky='w', pady=(6, 2))
        self.labelPicker = SearchableComboBox(
            self.body, values=list(waypointsLabels),
            placeholder='Label suchen …')
        self.labelPicker.grid(row=8, column=0, columnspan=2, sticky='ew',
                              pady=(0, 6))
        current = options.get('waypointLabelToRedirect', '')
        if current:
            self.labelPicker.set(current)

    def _amountRow(self, row, label, current):
        customtkinter.CTkLabel(
            self.body, text=label, font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=row, column=0, columnspan=2, sticky='w', pady=(4, 2))
        entry = customtkinter.CTkEntry(
            self.body, validate='key',
            validatecommand=(self.register(positiveInt), '%P'),
        )
        entry.grid(row=row + 1, column=0, columnspan=2, sticky='ew')
        if current is not None:
            entry.insert(0, str(current))
        return entry

    def confirm(self):
        values = (
            ('Health Potions', self.healthEntry.get()),
            ('Mana Potions', self.manaEntry.get()),
            ('Cap', self.capEntry.get()),
        )
        for label, value in values:
            if not positiveInt(value) or value == '':
                return self.fail(f'{label}: Zahl groesser als 0 angeben.')
        if self.labelPicker.get() not in \
                self.labelPicker.all_values:
            return self.fail('Ziel-Label aus der Liste waehlen.')
        self.onConfirm(None, {
            'minimumAmountOfHealthPotions': int(self.healthEntry.get()),
            'minimumAmountOfManaPotions': int(self.manaEntry.get()),
            'minimumAmountOfCap': int(self.capEntry.get()),
            'waypointLabelToRedirect': self.labelPicker.get(),
            'healthEnabled': self.healthSwitch.get() == 1,
        })
        self.destroy()
