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

import wx

from outwiker.api.gui.actions import BaseAction
from outwiker.api.core.tree import testreadonly
from outwiker.api.core.exceptions import ReadonlyException

from .i18n import get_
from .sourceconfig import SourceConfig
from .insertdialog import InsertDialog
from .insertdialogcontroller import InsertDialogController


class InsertSourceAction(BaseAction):
    """
    Open dialog to insert (:source:) command
    """

    stringId = "Source_InsertSource"

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

        global _
        _ = get_()

    @property
    def title(self):
        return _("Source Code (:source ...:)")

    @property
    def description(self):
        return _(
            "Source plugin. Insert (: source... :) command for source code highlighting"
        )

    def run(self, params):
        self._insertCommand()

    @testreadonly
    def _insertCommand(self):
        """
        Insert (:source:) command into editor
        """
        if self._application.selectedPage.readonly:
            raise ReadonlyException()

        config = SourceConfig(self._application.config)

        with InsertDialog(self._application.mainWindow) as dlg:
            dlgController = InsertDialogController(
                self._application.selectedPage, dlg, config
            )
            resultDlg = dlgController.showDialog()

            if resultDlg == wx.ID_OK:
                command = dlgController.getCommandStrings()
                pageView = self._getPageView()
                pageView.codeEditor.turnText(command[0], command[1])

            dlg.Destroy()

    def _getPageView(self):
        """
        Get pointer to the page view panel
        """
        return self._application.mainWindow.pageView
