"""Kombos-Seite: Spell-Kombos als Liste mit Master-Schalter.

Doppelklick öffnet den Kombo-Editor. Gleiche Context-Aufrufe wie vorher.
"""
from tkinter import ttk

import customtkinter

from src.ui import theme
from src.ui.widgets import Card
from .comboModal import ComboModal


class ComboSpellsPage(customtkinter.CTkFrame):
    def __init__(self, master, context):
        super().__init__(master, fg_color='transparent')
        self.context = context
        self.comboModal = None
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, 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.configure(
            'Treeview.Heading', background=theme.ELEVATED,
            foreground=theme.ACCENT, borderwidth=0,
        )
        style.map('Treeview', background=[('selected', theme.ACCENT)],
                  foreground=[('selected', '#FFFFFF')])

        card = Card(self, 'Kombos', 'Doppelklick zum Bearbeiten',
                    toggled=self.onToggleEnabledButton,
                    toggle_initial=self.context.context['ng_comboSpells']['enabled'])
        card.grid(row=0, column=0, sticky='nsew')
        card.body.grid_rowconfigure(0, weight=1)
        card.body.grid_columnconfigure((0, 1), weight=1)

        self.table = ttk.Treeview(
            card.body, columns=('name', 'enabled'), show='headings')
        self.table.grid(row=0, column=0, columnspan=2, sticky='nsew')
        self.table.heading('name', text='Name')
        self.table.heading('enabled', text='Aktiv')
        self.table.bind('<Double-1>', self.onComboDoubleClick)

        customtkinter.CTkButton(
            card.body, text='Neue Kombo', height=34, corner_radius=8,
            fg_color=theme.ACCENT, hover_color=theme.ACCENT_HOVER,
            command=self.addCombo,
        ).grid(row=1, column=0, sticky='ew', padx=(0, 4), pady=(8, 0))
        customtkinter.CTkButton(
            card.body, text='Auswahl löschen', height=34, corner_radius=8,
            fg_color=theme.ELEVATED, hover_color=theme.DANGER,
            text_color=theme.MUTED, command=self.deleteSelectedCombos,
        ).grid(row=1, column=1, sticky='ew', padx=(4, 0), pady=(8, 0))

        self._reloadTable()

    def _reloadTable(self):
        self.table.delete(*self.table.get_children())
        for combo in self.context.context['ng_comboSpells']['items']:
            self.table.insert('', 'end', values=(
                combo['name'], 'ja' if combo['enabled'] else 'nein'))

    def addCombo(self):
        self.context.addCombo({
            'enabled': False,
            'name': 'Neue Kombo',
            'creatures': {'compare': 'lessThan', 'value': 5},
            'spells': [],
            'currentSpellIndex': 0,
        })
        self._reloadTable()

    def deleteSelectedCombos(self):
        for row in self.table.selection():
            self.context.removeComboByIndex(self.table.index(row))
        self._reloadTable()

    def onComboDoubleClick(self, event):
        item = self.table.identify_row(event.y)
        if not item:
            return
        index = self.table.index(item)
        combo = self.context.context['ng_comboSpells']['items'][index]
        if self.comboModal is None or not self.comboModal.winfo_exists():
            self.comboModal = ComboModal(
                self, combo=combo, context=self.context, index=index)

    def onToggleEnabledButton(self):
        self.context.toggleComboSpells(
            not self.context.context['ng_comboSpells']['enabled'])
