# -*- coding: utf-8 -*-

import wx

from outwiker.api.gui.actions import BaseAction
from outwiker.api.gui.dialogs import TestedDialog, MessageBox
from outwiker.api.gui.images import readImage
from outwiker.api.gui.defines import BUTTON_ICON_WIDTH, BUTTON_ICON_HEIGHT

from .i18n import get_
from .sessionstorage import SessionStorage
from .misc import getImagePath


class EditSessionsAction(BaseAction):
    """
    Действие для вызова диалога редактирования сессий
    """

    def __init__(self, application, guicreator):
        self._application = application
        self._guicreator = guicreator

        global _
        _ = get_()

    stringId = "Sessions_EditSession"

    @property
    def title(self):
        return _("Edit sessions...")

    @property
    def description(self):
        return _("Edit (rename or delete) sessions")

    def run(self, params):
        storage = SessionStorage(self._application.config)
        names = sorted(storage.getSessions().keys())

        if len(names) == 0:
            MessageBox(_("Not created any session"), _("Error"), wx.ICON_ERROR | wx.OK)
            return

        with EditSessionsDialog(
            self._application.mainWindow, self._application, self._guicreator
        ) as dlg:
            dlg.ShowModal()


class EditSessionsDialog(TestedDialog):
    def __init__(self, parent, application, guicreator):
        """
        parent - родительское окно
        application - экземпляр класса Application
        guicreator - экземпляр класса GuiCreator
        """
        super(EditSessionsDialog, self).__init__(
            parent, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
        )

        self._application = application
        self._guicreator = guicreator

        self._storage = SessionStorage(self._application.config)

        self.SetTitle(_("Edit Sessions"))
        self.__createGui()

        self._removeButton.Bind(wx.EVT_BUTTON, handler=self._onRemove)
        self._renameButton.Bind(wx.EVT_BUTTON, handler=self._onRename)

        self._updateSessionsList()
        self.Center(wx.BOTH)
        self.SetSize((350, 250))

    def _updateSessionsList(self):
        names = sorted(self._storage.getSessions().keys())
        self._actionsList.Clear()
        self._actionsList.AppendItems(names)

    def _onRemove(self, event):
        name = self._actionsList.GetStringSelection()
        if len(name) == 0:
            return

        if (
            MessageBox(
                _('Remove session "{}"?').format(name),
                _("Remove session?"),
                wx.ICON_QUESTION | wx.YES | wx.NO,
            )
            == wx.YES
        ):
            self._storage.remove(name)
            self._updateSessionsList()
            self._guicreator.updateMenu()

    def _onRename(self, event):
        name = self._actionsList.GetStringSelection()
        if len(name) == 0:
            return

        with wx.TextEntryDialog(
            self, _("Enter new session name"), _("Rename session"), name
        ) as dlg:
            if dlg.ShowModal() == wx.ID_OK:
                newname = dlg.GetValue().strip()

                if len(newname) == 0:
                    MessageBox(
                        _("Session name is empty").format(newname),
                        _("Invalid session name"),
                        wx.ICON_ERROR | wx.OK,
                    )
                    return

                # Проверим, что не ввели имя сессии, совпадающее с существующей
                # сессией (кроме случая, что не изменили имя)
                if newname != name and newname in self._storage.getSessions():
                    MessageBox(
                        _('Session "{}" already exists').format(newname),
                        _("Invalid session name"),
                        wx.ICON_ERROR | wx.OK,
                    )
                    return

                self._storage.rename(name, newname)
                self._updateSessionsList()
                self._guicreator.updateMenu()

    def __createGui(self):
        mainSizer = wx.FlexGridSizer(rows=2, cols=0, vgap=0, hgap=0)
        mainSizer.AddGrowableRow(0)
        mainSizer.AddGrowableCol(0)

        actionsSizer = wx.FlexGridSizer(cols=2)
        actionsSizer.AddGrowableCol(0)
        actionsSizer.AddGrowableRow(0)

        self._actionsList = wx.ListBox(self)
        self._actionsList.SetMinSize((250, 150))

        mainButtonsSizer = wx.BoxSizer(wx.VERTICAL)

        self._renameButton = wx.BitmapButton(
            self,
            wx.ID_ANY,
            readImage(
                getImagePath("rename.svg"), BUTTON_ICON_WIDTH, BUTTON_ICON_HEIGHT
            ),
        )
        self._renameButton.SetToolTip(_("Rename session..."))

        self._removeButton = wx.BitmapButton(
            self,
            wx.ID_ANY,
            readImage(
                getImagePath("remove.svg"), BUTTON_ICON_WIDTH, BUTTON_ICON_HEIGHT
            ),
        )
        self._removeButton.SetToolTip(_("Remove session..."))

        mainButtonsSizer.Add(self._renameButton, 0, wx.ALL, border=2)
        mainButtonsSizer.Add(self._removeButton, 0, wx.ALL, border=2)

        actionsSizer.Add(self._actionsList, 1, wx.EXPAND | wx.ALL, border=2)
        actionsSizer.Add(mainButtonsSizer, 1, wx.ALL, border=2)

        buttonsSizer = self.CreateButtonSizer(wx.OK)
        mainSizer.Add(actionsSizer, 1, wx.EXPAND | wx.ALL, border=2)
        mainSizer.Add(buttonsSizer, 1, wx.ALIGN_RIGHT | wx.ALL, border=2)

        self.SetSizer(mainSizer)
        self.Fit()

    @property
    def sessionName(self):
        return self._sessionComboBox.GetValue()
