import os
import time
import re
from qtpy.QtWidgets import QHBoxLayout, QMessageBox
from qtpy.QtGui import QKeyEvent, QFocusEvent, QMouseEvent
from qtpy.QtCore import Qt

from pyminer2.extensions.packages.qt_vditor.client import Window
from pyminer2.extensions.packages.code_editor.codeeditor.abstracteditor import PMAbstractEditor

from pmgwidgets import in_unit_test


class PMMarkdownEditor(PMAbstractEditor):
    def __init__(self, parent=None):
        super(PMMarkdownEditor, self).__init__(parent=parent)
        self.textEdit = Window(url='http://127.0.0.1:5000/qt_vditor')
        self._path = ''
        self.setLayout(QHBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self.textEdit)

    def set_lib(self, extension_lib):
        """
        获取extension_lib插件扩展库
        Args:
            extension_lib:

        Returns:

        """
        self.extension_lib = extension_lib

    def load_file(self, path: str):
        """
        加载文件
        Args:
            path:

        Returns:

        """
        self._path = path
        self.textEdit.load_file(path)

    def update_settings(self, settings):
        """
        加载编辑器的设置
        Args:
            settings:

        Returns:

        """
        pass

    def filename(self):
        """
        获取当前文件名
        Returns:

        """
        return os.path.basename(self._path)

    def modified(self) -> bool:
        """
        获取当前文件是否被修改
        Returns:

        """
        return False

    def slot_about_close(self, save_all=False):
        """
        当点击右上角叉号时触发的方法，如果检测到未保存的更改，会阻止关闭并弹出窗口让用户确认保存。
        Args:
            save_all:

        Returns:

        """

        if not self.modified():
            return QMessageBox.Discard
        buttons = QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel
        if save_all:
            buttons |= QMessageBox.SaveAll  # 保存全部
            buttons |= QMessageBox.NoToAll  # 放弃所有
        ret = QMessageBox.question(self, self.tr('Save'), self.tr('Save file "{0}"?').format(self.filename()), buttons,
                                   QMessageBox.Save)
        if ret == QMessageBox.Save or ret == QMessageBox.SaveAll:
            if not self.save():
                return QMessageBox.Cancel
        return ret

    def slot_save(self) -> None:
        self.textEdit.save_file()
        self.last_save_time = time.time()

    def slot_file_modified_externally(self):
        self.last_save_time = time.time()

    def keyPressEvent(self, a0: QKeyEvent) -> None:
        super().keyPressEvent(a0)
        if a0.key() == Qt.Key_S and a0.modifiers() == Qt.ControlModifier:
            self.slot_save()
        print(a0)

    def get_code(self) -> str:
        with open(self._path, 'r', encoding='utf8') as f:
            text = f.read()
        code_blocks = re.findall('```python([\s\S]*?)```', text)
        if len(code_blocks) > 1:
            QMessageBox.warning(self, '未集成功能', '暂不支持运行含有两段及以上代码的Markdown文件！')
            return ''
        else:
            return code_blocks[0]

    def mousePressEvent(self, a0: QMouseEvent) -> None:
        print('mouse pressed')
        super(PMMarkdownEditor, self).mousePressEvent(a0)
