"""
Un plugin destiné à Pampi, pour insérer une image dans l'éditeur
à la position courante du curseur.
"""

try:
    from PyQt5 import QtCore, QtWidgets, QtGui
except:
    from PyQt4 import QtCore, QtGui as QtWidgets, QtGui

import os, re

from ._template import Plugin as Template

from .plugin_rc import *

class Plugin(Template):
    """
    Le constructeur prend comme paramètre la fenêtre principale
    de l'application. Il doit définir les propriété name et action
    @param mainWindow la fenêtre pincipale
    """
    def __init__(self, mainWindow):
        iconPath = ':/img/icons/image.png'
        title = QtCore.QCoreApplication.translate("main","Insert an image")
        self.parent = mainWindow
        Template.__init__(self, mainWindow,
                          name = "image", iconPath = iconPath, title = title)
        return
    
    img_pattern = re.compile(r"^!\[.*\]\((.*)\)", re.MULTILINE)
    img_template = "![]({})\n"
    
    def _run(self):
        """
        Fonction de rappel pour le plugin
        """
        thedir = self.dataDir
        fragment = self.getSelected()
        m = self.img_pattern.search(fragment)
        if m:
            thedir = os.path.join(
                self.presentationsDir, os.path.dirname(m.group(1)))
        fn, _ = QtWidgets.QFileDialog.getOpenFileName(
            self.parent,
            QtCore.QCoreApplication.translate("main","Open Image File"),
            thedir,
            QtCore.QCoreApplication.translate("main","Images (*.gif *.png *.xpm *.jpg *.jpeg)"));
        if fn:
            fn = self.simplifyDir(fn)
            self.insertSelected(self.img_template.format(fn))
        return
        
    
