from pathlib import Path

from PySide2.QtCore import Signal
from PySide2.QtGui import QDragEnterEvent, QDragMoveEvent, QDropEvent
from PySide2.QtWidgets import QListWidget


class QListWidgetCustom(QListWidget):
    """
    Поддержка механизма drag and drop.
    """

    paths_dropped = Signal(list)
    """
    list[Path]
    """

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, e: QDragEnterEvent) -> None:
        if e.mimeData().hasUrls():
            e.accept()
        else:
            e.ignore()

    def dragMoveEvent(self, e: QDragMoveEvent) -> None:
        if e.mimeData().hasUrls():
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e: QDropEvent) -> None:
        if e.mimeData().hasUrls():
            e.accept()
            urls = e.mimeData().urls()
            file_names = [Path(url.toLocalFile()) for url in urls]
            self.paths_dropped.emit(file_names)
        else:
            e.ignore()
