"""Kombo-Editor: Bedingung und Spell-Liste einer Kombo bearbeiten.

Gleiche Context-Aufrufe wie vorher, aber als klare Editor-Karte:
Schalter, Name, Bedingung und Spell-Tabelle mit Doppelklick-Bearbeitung.
"""
from tkinter import StringVar, ttk

import customtkinter

from src.ui import theme
from src.ui.widgets import Card
from .comboSpellModal import ComboSpellModal

COMPARE_OPTIONS = ['lessThan', 'lessThanOrEqual', 'greaterThan',
                   'greaterThanOrEqual']


class ComboModal(customtkinter.CTkToplevel):
    def __init__(self, parent, combo=None, context=None, index=None):
        super().__init__(parent)
        self.context = context
        self.index = index
        self.comboSpellModal = None

        self.title('Kombo bearbeiten')
        self.resizable(False, True)
        self.configure(fg_color=theme.BG)
        self.geometry('560x520')
        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')])

        settings = Card(self, 'Bedingung')
        settings.grid(row=0, column=0, padx=14, pady=(14, 6), sticky='ew')
        settings.body.grid_columnconfigure(1, weight=1)

        self.enabledSwitch = customtkinter.CTkSwitch(
            settings.body, text='Aktiviert', progress_color=theme.ACCENT,
            command=self.onToggleEnabledButton,
        )
        self.enabledSwitch.grid(row=0, column=0, columnspan=2, sticky='w',
                                pady=2)
        if combo['enabled']:
            self.enabledSwitch.select()

        customtkinter.CTkLabel(
            settings.body, text='Name', font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=1, column=0, sticky='w', pady=3)
        self.labelEntryVar = StringVar(value=combo['name'])
        self.labelEntryVar.trace_add('write', self.changeComboName)
        customtkinter.CTkEntry(
            settings.body, textvariable=self.labelEntryVar,
        ).grid(row=1, column=1, sticky='ew', padx=(8, 0), pady=3)

        customtkinter.CTkLabel(
            settings.body, text='Wenn Kreaturen', font=theme.font(12),
            text_color=theme.MUTED,
        ).grid(row=2, column=0, sticky='w', pady=3)
        conditionRow = customtkinter.CTkFrame(
            settings.body, fg_color='transparent')
        conditionRow.grid(row=2, column=1, sticky='ew', padx=(8, 0), pady=3)
        conditionRow.grid_columnconfigure((0, 1), weight=1)
        self.compareCondition = customtkinter.CTkComboBox(
            conditionRow, values=COMPARE_OPTIONS, state='readonly',
            command=self.onChangeCompare,
        )
        self.compareCondition.set(combo['creatures']['compare'])
        self.compareCondition.grid(row=0, column=0, sticky='ew', padx=(0, 4))
        self.compareValueVar = StringVar(value=str(combo['creatures']['value']))
        self.compareValueVar.trace_add('write', self.changeCompareValue)
        customtkinter.CTkEntry(
            conditionRow, textvariable=self.compareValueVar, width=70,
        ).grid(row=0, column=1, sticky='e')

        spells = Card(self, 'Spells', 'Doppelklick zum Bearbeiten')
        spells.grid(row=1, column=0, padx=14, pady=(0, 6), sticky='nsew')
        spells.body.grid_rowconfigure(0, weight=1)
        spells.body.grid_columnconfigure((0, 1), weight=1)

        self.table = ttk.Treeview(
            spells.body, columns=('name', 'hotkey'), show='headings')
        self.table.grid(row=0, column=0, columnspan=2, sticky='nsew')
        self.table.heading('name', text='Spell')
        self.table.heading('hotkey', text='Hotkey')
        self.table.bind('<Double-1>', self.onSpellDoubleClick)

        customtkinter.CTkButton(
            spells.body, text='Spell hinzufügen', height=32, corner_radius=8,
            fg_color=theme.ACCENT, hover_color=theme.ACCENT_HOVER,
            command=self.addSpell,
        ).grid(row=1, column=0, sticky='ew', padx=(0, 4), pady=(8, 0))
        customtkinter.CTkButton(
            spells.body, text='Auswahl entfernen', height=32, corner_radius=8,
            fg_color=theme.ELEVATED, hover_color=theme.DANGER,
            text_color=theme.MUTED, command=self.removeSelectedSpells,
        ).grid(row=1, column=1, sticky='ew', padx=(4, 0), pady=(8, 0))

        self._reloadTable(combo)

    def _reloadTable(self, combo=None):
        self.table.delete(*self.table.get_children())
        items = self.context.context['ng_comboSpells']['items'][self.index]
        for spell in items['spells']:
            self.table.insert('', 'end', values=(
                spell['name'], spell['hotkey']))

    def addSpell(self):
        self.context.addSpellByIndex(self.index, {
            'name': 'exori', 'hotkey': 'f4',
        })
        self._reloadTable()

    def removeSelectedSpells(self):
        for row in self.table.selection():
            indexSecond = self.table.index(row)
            self.context.removeSpellByIndex(self.index, indexSecond)
        self._reloadTable()

    def changeComboName(self, var, index, mode):
        self.context.changeComboName(self.labelEntryVar.get(), self.index)

    def changeCompareValue(self, var, index, mode):
        self.context.changeCompareValue(self.compareValueVar.get(), self.index)

    def onToggleEnabledButton(self):
        self.context.toggleSingleCombo(
            self.enabledSwitch.get() == 1, self.index)

    def onChangeCompare(self, _):
        self.context.setCompare(self.compareCondition.get(), index=self.index)

    def onSpellDoubleClick(self, event):
        item = self.table.identify_row(event.y)
        if not item:
            return
        indexSecond = self.table.index(item)
        spell = self.context.context['ng_comboSpells']['items'][
            self.index]['spells'][indexSecond]
        if self.comboSpellModal is None or not self.comboSpellModal.winfo_exists():
            self.comboSpellModal = ComboSpellModal(
                self, spell=spell, context=self.context, index=self.index,
                indexSecond=indexSecond)
