from __future__ import annotations

from ..Qt import QtWidgets, QtCore

from nmreval.lib.logger import logger
from ..graphs.graphwindow import QGraphWindow


class MdiAreaTile(QtWidgets.QMdiArea):
    newData = QtCore.pyqtSignal(list)

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

    def tileSubWindowsVertically(self):
        window_list = self.subWindowList()
        rect = QtCore.QRect(0, 0, self.width(), int(self.height() / len(window_list)))
        pos = QtCore.QPoint(0, 0)

        for win in window_list:
            win.setGeometry(rect)
            win.move(pos)

            pos.setY(pos.y() + win.height())

    def tileSubWindowsHorizontally(self):
        window_list = self.subWindowList()
        rect = QtCore.QRect(0, 0, int(self.width() / len(window_list)), self.height())
        pos = QtCore.QPoint(0, 0)

        for win in window_list:
            win.setGeometry(rect)
            win.move(pos)

            pos.setX(pos.x() + win.width())

    def addSubWindow(self, widget: QtWidgets.QWidget, flags: QtCore.Qt.WindowFlags = QtCore.Qt.WindowFlags()) -> QtWidgets.QMdiSubWindow | None:
        subwindow = super().addSubWindow(widget)
        subwindow.setOption(QtWidgets.QMdiSubWindow.RubberBandMove, True)
        subwindow.setOption(QtWidgets.QMdiSubWindow.RubberBandResize, True)
        subwindow.setMinimumHeight(240)
        subwindow.setMinimumWidth(360)

        return subwindow

    def setActiveSubWidget(self, key: str):
        for win in self.subWindowList():
            wdgt = win.widget()
            if isinstance(wdgt, QGraphWindow) and wdgt.id == key:
                self.setActiveSubWindow(win)
                break

    def dropEvent(self, evt):
        if evt.mimeData().hasUrls():
            files = [str(url.toLocalFile()) for url in evt.mimeData().urls()]
            self.newData.emit(files)
