'''
Hérite de QLabel, accepte les drop de fichiers et lit leur

@author: olivier.massot, nov. 2017
'''
import re

from PyQt5.Qt import QLabel, Qt, pyqtSignal, QTextCodec
from path import Path

from core import constants


class DropLabel(QLabel):
    dropped = pyqtSignal()

    def __init__(self, parent):
        super(QLabel, self).__init__(parent)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls:
            event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        data = event.mimeData().data("FileGroupDescriptorW")
        data = QTextCodec.codecForName("UTF-16").toUnicode(data)
        data = re.findall(r"[\w\-. ]+", data)

        if event.mimeData().hasFormat("FileGroupDescriptor"):
            event.setDropAction(Qt.CopyAction)
            event.accept()

            # Get the file's name from mime data
            data = event.mimeData().data("FileGroupDescriptorW")
            data = QTextCodec.codecForName("UTF-16").toUnicode(data)
            names = re.findall(r"[\w\-. ]+", data)
            if len(names) > 1:
                raise IOError("Vous ne pouvez pas traiter plus d'un fichier à la fois!")
            filename = Path(names[0])
            if not filename.ext == ".xml":
                raise IOError("Le fichier doit être un fichier '.xml'.")

            # Write the file in a temporary directory
            with open(constants.TMPDIR / filename, 'wb') as f:
                f.write(event.mimeData().data("FileContents"))
            self.url = (constants.TMPDIR / filename)
            self.dropped.emit()

        elif event.mimeData().hasUrls:
            event.setDropAction(Qt.CopyAction)
            event.accept()
            links = [url.toLocalFile() for url in event.mimeData().urls()]
            self.url = links[0]
            self.dropped.emit()

        else:
            event.ignore()
