from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QScrollArea,
    QWidget,
    QPushButton,
    QLineEdit,
    QMessageBox,
)

from .ButtonGroup import ButtonGroup
from .GraphRequester import GraphRequester


class PlotterDialog(QDialog):
    focused_line_edit = None

    def __init__(
        self,
        variable_full_names: dict[str, str],
        function_full_names: dict[str, str],
        # variable_values: dict[str, np.ndarray],
    ):
        super().__init__()

        self.setWindowTitle("Графопостроитель")

        layout_boss = QVBoxLayout()  # главный лояут

        self.scroll = QScrollArea()

        self.scroll.verticalScrollBar().rangeChanged.connect(self.scroll_bottom)

        scrollWidget = QWidget()

        # self.scroll.setFrameShape(QFrame.NoFrame)
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        self.inputs_layout = QVBoxLayout()  # лаяут первой трети
        self.inputs_layout.addStretch(1)

        self.num_of_input = 0  # инициализация первого графика
        self.add_input()

        scrollWidget.setLayout(self.inputs_layout)

        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(scrollWidget)

        layout_boss.addWidget(self.scroll)

        Button_make_fun_button = QPushButton("+")
        Button_make_fun_button.clicked.connect(self.add_input)
        Button_make_fun_button.setFixedWidth(80)
        layout_boss.addWidget(Button_make_fun_button, alignment=Qt.AlignRight)

        layout_boss.addWidget(
            ButtonGroup(
                "Переменные",
                full_names=variable_full_names,
                buttons_action=self.insert_variable,
            )
        )
        layout_boss.addWidget(
            ButtonGroup(
                "Функции",
                full_names=function_full_names,
                buttons_action=self.insert_function,
            )
        )

        self.setLayout(layout_boss)

    def add_input(self):
        self.num_of_input += 1

        graph_requester = GraphRequester(self.num_of_input)

        for line_edit in (graph_requester.LineEditX, graph_requester.LineEditY):
            line_edit.focused_in.connect(
                lambda line_edit=line_edit: self.set_focused_line_edit(line_edit)
            )

        graph_requester.LineEditGraf.focused_in.connect(
            lambda: self.set_focused_line_edit(None)
        )

        self.inputs_layout.insertWidget(self.inputs_layout.count() - 1, graph_requester)

        graph_requester.LineEditGraf.setFocus()

    def set_focused_line_edit(self, line_edit: QLineEdit | None):
        self.focused_line_edit = line_edit

    def scroll_bottom(self):
        self.scroll.verticalScrollBar().setValue(
            self.scroll.verticalScrollBar().maximum()
        )

    def insert_string(self, string: str, string_cursor_padding=-1):
        line_edit = self.focused_line_edit

        if line_edit is None:
            QMessageBox(
                QMessageBox.Warning,
                "Ошибка",
                "Выберите поле ввода выражения",
            ).exec()

            return

        cusor_pos = line_edit.cursorPosition()
        text = line_edit.text()

        if string_cursor_padding < 1:
            string_cursor_padding = len(string)

        line_edit.setText(text[:cusor_pos] + string + text[cusor_pos:])
        line_edit.setCursorPosition(cusor_pos + string_cursor_padding)

        self.scroll.ensureWidgetVisible(line_edit)
        line_edit.setFocus()

    def insert_variable(self, name: str):
        self.insert_string(f" {name} ")

    def insert_function(self, name: str):
        string = f" {name}()"
        self.insert_string(string, len(string) - 1)  # len - 1 for cursor between braces
