"""Ignorierte Kreaturen: direkt aus der Wiki-Liste suchen und hinzufuegen.

Statt Platzhalter-Eintraegen plus Doppelklick-Dialog: Suchfeld mit der
kompletten Kreaturenliste (src.wiki.creatures) und Entfernen-Button.
"""
from tkinter import ttk

import customtkinter

from src.ui import theme
from src.ui.widgets import SearchableComboBox
from src.wiki.creatures import creatures


class IgnoreCreaturesPage(customtkinter.CTkToplevel):
    def __init__(self, context):
        super().__init__()
        self.context = context
        self.title('Ignorierte Kreaturen')
        self.resizable(False, True)
        self.configure(fg_color=theme.BG)
        self.geometry('460x420')
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(1, weight=1)

        style = ttk.Style()
        style.theme_use('default')
        style.configure(
            'Treeview', background=theme.ELEVATED, foreground=theme.TEXT,
            fieldbackground=theme.ELEVATED, borderwidth=0, rowheight=26,
        )
        style.map('Treeview', background=[('selected', theme.ACCENT)],
                  foreground=[('selected', '#FFFFFF')])

        addBar = customtkinter.CTkFrame(self, fg_color='transparent')
        addBar.grid(row=0, column=0, padx=14, pady=(14, 6), sticky='ew')
        addBar.grid_columnconfigure(0, weight=1)
        self.picker = SearchableComboBox(
            addBar, values=sorted(creatures.keys()),
            placeholder='Kreatur suchen …')
        self.picker.grid(row=0, column=0, sticky='ew', padx=(0, 8))
        customtkinter.CTkButton(
            addBar, text='Hinzufügen', width=110, height=32,
            corner_radius=8, fg_color=theme.ACCENT,
            hover_color=theme.ACCENT_HOVER, command=self.addCreature,
        ).grid(row=0, column=1)

        self.table = ttk.Treeview(self, columns=('name',), show='headings')
        self.table.grid(row=1, column=0, padx=14, pady=(0, 6), sticky='nsew')
        self.table.heading('name', text='Wird ignoriert')

        self.errorLabel = customtkinter.CTkLabel(
            self, text='', font=theme.font(11), text_color=theme.DANGER,
        )
        self.errorLabel.grid(row=2, column=0, padx=14, sticky='w')

        customtkinter.CTkButton(
            self, text='Auswahl entfernen', height=32, corner_radius=8,
            fg_color=theme.ELEVATED, hover_color=theme.DANGER,
            text_color=theme.MUTED, command=self.deleteSelectedCreatures,
        ).grid(row=3, column=0, padx=14, pady=(2, 14), sticky='ew')

        self._reload()

    def _reload(self):
        self.table.delete(*self.table.get_children())
        for creature in self.context.context['ignorable_creatures']:
            self.table.insert('', 'end', values=(creature,))

    def addCreature(self):
        name = self.picker.get().strip()
        if name not in creatures:
            self.errorLabel.configure(
                text='Kreatur aus der Liste waehlen.')
            return
        if name in self.context.context['ignorable_creatures']:
            self.errorLabel.configure(text=f'"{name}" ist schon in der Liste.')
            return
        self.errorLabel.configure(text='')
        self.picker.set('')
        self.context.addIgnorableCreature(name)
        self._reload()

    def deleteSelectedCreatures(self):
        for row in self.table.selection():
            name = self.table.item(row)['values'][0]
            index = self.context.context['ignorable_creatures'].index(name)
            self.context.removeIgnorableCreatureByIndex(index)
        self._reload()
