from __future__ import annotations

from PyQt5 import QtCore, QtGui, QtWidgets

from .._py.ellipsewidget import Ui_ellipsewidget
from .._py.linedrawwidget import Ui_linewidget
from .._py.rectanglewidget import Ui_rectanglewidget
from .._py.multipointwidget import Ui_multipointwidget
from .._py.textdrawidget import Ui_textwidget

__all__ = ['LineWidget', 'MultiPointWidget', 'RectangleWidget', 'EllipseWidget', 'TextWidget']


def parse_point(x_widget: QtWidgets.QLineEdit, y_widget: QtWidgets.QLineEdit) -> None | tuple[float, float]:
    x = x_widget.text()
    if not x:
        return
    y = y_widget.text()
    if not y:
        return

    try:
        return float(x), float(y)
    except ValueError:
        return


class LineWidget(QtWidgets.QWidget, Ui_linewidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.pos_lineedit.setValidator(QtGui.QDoubleValidator())


    def collect_args(self) -> dict | None:
        pos = self.pos_lineedit.text()
        try:
            pos = float(pos)
        except ValueError:
            return

        dic = {
            'color': self.color_box.currentData(),
            'pos': pos,
            'angle': self.orient_combobox.currentIndex() * 90
        }

        return dic

    def set_args(self, pos: float = None, angle: int = None, color = None):
        self.pos_lineedit.setText(str(pos))
        self.orient_combobox.setCurrentIndex(angle%90)
        self.color_box.setCurrentIndex(self.color_box.findData(color))


class MultiPointWidget(QtWidgets.QWidget, Ui_multipointwidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.new_point()
        self.new_point()

    @QtCore.pyqtSlot(name='on_addButton_clicked')
    def new_point(self):
        row = self.table_widget.rowCount()
        self.table_widget.setRowCount(row+1)
        placeholder = ['x', 'y']
        for column in range(2):
            line_edit = QtWidgets.QLineEdit()
            line_edit.setFrame(False)
            line_edit.setPlaceholderText(placeholder[column])
            line_edit.setValidator(QtGui.QDoubleValidator())

            self.table_widget.setCellWidget(row, column, line_edit)

    @QtCore.pyqtSlot(name='on_removeButton_clicked')
    def less_point(self):
        if self.table_widget.rowCount() > 2:
            self.table_widget.removeRow(self.table_widget.rowCount()-1)

    def collect_args(self) -> dict | None:

        pts = []
        if self.table_widget.rowCount() < 2:
            return

        for row in range(self.table_widget.rowCount()):
            next_pt = parse_point(self.table_widget.cellWidget(row, 0), self.table_widget.cellWidget(row, 1))
            if next_pt is None:
                return
            pts.append(next_pt)

        dic = {
            'color': self.color_box.currentData(QtCore.Qt.UserRole),
            'pts': pts,
            'closed': self.loop_checkbox.isChecked(),
        }

        return dic

    def set_args(self, x: tuple = None, y: tuple = None, closed: bool = True, color=None):
        self.table_widget.clear()
        self.table_widget.setRowCount(0)

        for row, (x_i, y_i) in enumerate(zip(x, y)):
            self.new_point()
            self.table_widget.cellWidget(row, 0).setText(str(x_i))
            self.table_widget.cellWidget(row, 1).setText(str(y_i))

        self.loop_checkbox.setChecked(closed)
        self.color_box.setCurrentIndex(self.color_box.findData(color))


class RectangleWidget(QtWidgets.QWidget, Ui_rectanglewidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.fill_box.insertItem(0, 'No fill', None)
        self.fill_box.setCurrentIndex(0)

        self.left_x.setValidator(QtGui.QDoubleValidator())
        self.left_y.setValidator(QtGui.QDoubleValidator())
        self.right_x.setValidator(QtGui.QDoubleValidator())
        self.right_y.setValidator(QtGui.QDoubleValidator())

    def set_args(self, left: tuple = (0, 0), right: tuple = (1, 1), color=None, fill=None):
        self.left_x.setText(str(left[0]))
        self.left_y.setText(str(left[1]))
        self.right_x.setText(str(right[0]))
        self.right_y.setText(str(right[1]))

        self.color_box.setCurrentIndex(self.color_box.findData(color, QtCore.Qt.UserRole))
        self.fill_box.setCurrentIndex(self.fill_box.findData(fill, QtCore.Qt.UserRole))

    def collect_args(self) -> dict | None:
        left = parse_point(self.left_x, self.left_y)
        if left is None:
            return

        right = parse_point(self.right_x, self.right_y)
        if right is None:
            return

        dic = {
            'color':  self.color_box.currentData(QtCore.Qt.UserRole),
            'fill': self.fill_box.currentData(QtCore.Qt.UserRole),
            'left': left,
            'right': right,
        }

        return dic


class EllipseWidget(QtWidgets.QWidget, Ui_ellipsewidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.fill_box.insertItem(0, 'No fill', None)
        self.fill_box.setCurrentIndex(0)

        self.center_x.setValidator(QtGui.QDoubleValidator())
        self.center_y.setValidator(QtGui.QDoubleValidator())
        self.width_line.setValidator(QtGui.QDoubleValidator())
        self.height_line.setValidator(QtGui.QDoubleValidator())

    def set_args(self, center: tuple = (0, 0), axes: tuple = (1, 1), color=None, fill=None):
        self.center_x.setText(str(center[0]))
        self.center_y.setText(str(center[1]))
        self.width_line.setText(str(axes[0]))
        self.width_line.setText(str(axes[1]))

        self.color_box.setCurrentIndex(self.color_box.findData(color, QtCore.Qt.UserRole))
        self.fill_box.setCurrentIndex(self.fill_box.findData(fill, QtCore.Qt.UserRole))

    def collect_args(self) -> dict | None:
        centre = parse_point(self.center_x, self.center_y)
        if centre is None:
            return
        axes = parse_point(self.width_line, self.height_line)
        if axes is None:
            return

        dic = {
            'color':  self.color_box.currentData(QtCore.Qt.UserRole),
            'fill': self.fill_box.currentData(QtCore.Qt.UserRole),
            'center': centre,
            'axes': axes,
        }

        return dic


class TextWidget(QtWidgets.QWidget, Ui_textwidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.center_x.setValidator(QtGui.QDoubleValidator())
        self.center_y.setValidator(QtGui.QDoubleValidator())

    def collect_args(self) -> dict | None:

        centre = parse_point(self.center_x, self.center_y)
        if centre is None:
            return

        dic = {
            'color': self.color_box.currentData(QtCore.Qt.UserRole),
            'pos': centre,
            'text': self.text_lineedit.text(),
        }

        return dic
