from PyQt5.QtGui import QImage, QTextDocument
from PyQt5.QtWidgets import QTextEdit
from path import Path
import uuid

IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.bmp']
FONT_SIZES = [7, 8, 9, 10, 11, 12, 13, 14, 18, 24, 36, 48, 64, 72, 96, 144, 288]
HTML_EXTENSIONS = ['.htm', '.html']


class WysiwygTextEdit(QTextEdit):
    def __init__(self, parent):
        super().__init__(parent)

    def canInsertFromMimeData(self, source):
        if source.hasImage():
            return True
        else:
            return super(WysiwygTextEdit, self).canInsertFromMimeData(source)

    def insertFromMimeData(self, source):

        cursor = self.textCursor()
        document = self.document()

        if source.hasUrls():

            for u in source.urls():
                file_ext = Path(str(u.toLocalFile())).splitext()
                if u.isLocalFile() and file_ext in IMAGE_EXTENSIONS:
                    image = QImage(u.toLocalFile())
                    document.addResource(QTextDocument.ImageResource, u, image)
                    cursor.insertImage(u.toLocalFile())

                else:
                    # If we hit a non-image or non-local URL break the loop and fall out
                    # to the super call & let Qt handle it
                    break

            else:
                # If all were valid images, finish here.
                return

        elif source.hasImage():
            image = source.imageData()
            uuid_ = uuid.uuid4().hex
            document.addResource(QTextDocument.ImageResource, uuid_, image)
            cursor.insertImage(uuid)
            return

        super(WysiwygTextEdit, self).insertFromMimeData(source)