"""
 CG-Plotter - extending the life of Mimaki CG series plotters, plotting SVG files
  produced in Inkscape and other packages on Windows or Linux platforms

Created by Joerg Beigang, Modified by Dave Glover April 2026

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

from PySide6.QtCore import Qt
from PySide6.QtGui import (
    QPainter,
    QFont
)
from PySide6.QtWidgets import (
    QWidget,
    QGraphicsView,
    QGraphicsScene,
    QHBoxLayout,
    QVBoxLayout,
    QLabel,
    QComboBox,
    QSpinBox,
    QSlider,
    QDoubleSpinBox,
    QPushButton,
    QCheckBox,
    QGroupBox,
    QSizePolicy,
    QDialog,
    QPlainTextEdit,
    QRadioButton

)

#include <QFont>
def build_gui(parent):
    # ---- Central widget ----
    central = QWidget()
    parent.setCentralWidget(central)

    main_layout = QHBoxLayout(central)
    main_layout.setContentsMargins(4, 4, 4, 4)
    main_layout.setSpacing(6)

    # =========================
    # Left control panel
    # =========================
    left_panel = QWidget()
    left_panel.setMinimumWidth(260)
    left_panel.setMaximumWidth(360)
    left_panel.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)

    left_layout = QVBoxLayout(left_panel)
    left_layout.setSpacing(8)
    # --- Plotter Settings ---
    parent.settings_btn = QPushButton("Plotter Settings")
    left_layout.addWidget(parent.settings_btn)

    # --- Tools group ---
    tool_group = QGroupBox("Tool Settings")
    tool_layout = QVBoxLayout(tool_group)

    parent.tools_check = QComboBox()
    parent.tools_check.addItem("Use selected plotter tool")
    parent.tools_check.addItem("Select a plotter tool")
    parent.tools_check.addItem("Use a custom tool")
    tool_layout.addWidget(parent.tools_check)
    parent.tools_check.setCurrentIndex(3) #--- set index to not used value to force correct tool settings

    parent.tool_type = QComboBox()
    parent.tool_type.addItem("Pen")
    parent.tool_type.addItem("Cut 1")
    parent.tool_type.addItem("Cut 2")
    parent.tool_type.addItem("Cut 3")
    parent.tool_type.addItem("Cut 4")
    parent.tool_type.addItem("Cut 5")
    tool_layout.addWidget(parent.tool_type)
    parent.tool_type.setCurrentIndex(5)


    parent.tools_text = QPlainTextEdit()
    parent.tools_text.setReadOnly(True)
    parent.tools_text.insertPlainText("Make sure the correct tool is selected on the plotter panel")
    tool_layout.addWidget(parent.tools_text)
    parent.tools_text.hide()

    speed_top = QHBoxLayout()
    speed_top.addWidget(QLabel("Speed"))
    parent.speed_spin = QSpinBox()
    parent.speed_spin.setRange(1, 50)
    parent.speed_spin.setValue(40)
    speed_top.addWidget(parent.speed_spin)
    tool_layout.addLayout(speed_top)

    parent.speed_slider = QSlider(Qt.Horizontal)
    parent.speed_slider.setRange(1, 50)
    parent.speed_slider.setValue(40)
    tool_layout.addWidget(parent.speed_slider)


    # Speed two-way connection
    parent.speed_spin.valueChanged.connect(parent.speed_slider.setValue)
    parent.speed_slider.valueChanged.connect(parent.speed_spin.setValue)

    pressure_top = QHBoxLayout()
    pressure_top.addWidget(QLabel("Force"))
    parent.pressure_spin = QSpinBox()
    parent.pressure_spin.setRange(1, 300)
    parent.pressure_spin.setValue(80)
    pressure_top.addWidget(parent.pressure_spin)
    tool_layout.addLayout(pressure_top)

    parent.pressure_slider = QSlider(Qt.Horizontal)
    parent.pressure_slider.setRange(1, 300)
    parent.pressure_slider.setValue(80)
    tool_layout.addWidget(parent.pressure_slider)

    parent.pressure_spin.valueChanged.connect(parent.pressure_slider.setValue)
    parent.pressure_slider.valueChanged.connect(parent.pressure_spin.setValue)

    offset_top = QHBoxLayout()
    offset_top.addWidget(QLabel("Knife Offset"))
    parent.offset_spin = QDoubleSpinBox()
    parent.offset_spin.setRange(0, 2)
    parent.offset_spin.setValue(0.3)
    parent.offset_spin.setSingleStep(0.05)
    offset_top.addWidget(parent.offset_spin)
    tool_layout.addLayout(offset_top)

    left_layout.addWidget(tool_group)

    # --- Options ---
    options_box = QGroupBox("Plot Options")
    options_layout = QVBoxLayout(options_box)

    frame_layout = QHBoxLayout()
    parent.box_check = QCheckBox("Frame (mm)")
    parent.box_spin = QSpinBox()
    parent.box_spin.setRange(1, 50)
    parent.box_spin.setValue(5)

    # checkbox_layout.addWidget(parent.box_check)
    frame_layout.addWidget(parent.box_check)
    frame_layout.addWidget(parent.box_spin)
    options_layout.addLayout(frame_layout)

    rotate_layout = QHBoxLayout()
    parent.rotate_check = QCheckBox("Rotate 90°")
    rotate_layout.addWidget(parent.rotate_check)

    parent.mirror_check = QCheckBox("Mirror")
    rotate_layout.addWidget(parent.mirror_check)
    options_layout.addLayout(rotate_layout)
        # scale svg
    scale_layout = QHBoxLayout()
    label_scale = QLabel("Scale SVG %")
    parent.scale_spin = QSpinBox()
    parent.scale_spin.setSingleStep(1)
    parent.scale_spin.setMinimum(1)
    parent.scale_spin.setMaximum(500)
    parent.scale_spin.setValue(100)

    scale_layout.addWidget(label_scale)
    scale_layout.addWidget(parent.scale_spin)
    options_layout.addLayout(scale_layout)

    #plotter position
    position_layout = QHBoxLayout()
    label_position = QLabel("Plot at ")
    parent.pos_left = QRadioButton("Left")
    parent.pos_centre = QRadioButton("Centre")
    parent.pos_right = QRadioButton("Right")
    parent.pos_right.setChecked(True)
    position_layout.addWidget(label_position)
    position_layout.addWidget(parent.pos_left)
    position_layout.addWidget(parent.pos_centre)
    position_layout.addWidget(parent.pos_right)
    options_layout.addLayout(position_layout)

    #plotter margin
    margin_layout = QHBoxLayout()
    label_margin = QLabel("Margin (mm)")
    parent.margin_spin = QSpinBox()
    parent.margin_spin.setSingleStep(1)
    parent.margin_spin.setRange(0, 500)
    parent.margin_spin.setValue(0)
    margin_layout.addWidget(label_margin)
    margin_layout.addWidget(parent.margin_spin)
    options_layout.addLayout(margin_layout)

    #Copies
    font = QFont('Arial', 20, QFont.Weight.Normal)
    copies_layout = QHBoxLayout()
    label_copies1 = QLabel("Copies")
    label_copies1a = QLabel("\u2B0C")
    label_copies1a.setFont(font)
    parent.copies_spin_horiz = QSpinBox()
    parent.copies_spin_horiz.setSingleStep(1)
    parent.copies_spin_horiz.setMaximum(99)
    parent.copies_spin_horiz.setMinimum(1)
    parent.copies_spin_horiz.setValue(1)
    label_copies2 = QLabel("\u2B0D")
    label_copies2.setFont(font)
    parent.copies_spin_vert = QSpinBox()
    parent.copies_spin_vert.setSingleStep(1)
    parent.copies_spin_vert.setMaximum(99)
    parent.copies_spin_vert.setValue(1)
    parent.copies_spin_vert.setMinimum(1)
    copies_layout.addWidget(label_copies1)
    copies_layout.addStretch()
    copies_layout.addWidget(label_copies1a)
    copies_layout.addStretch()
    copies_layout.addWidget(parent.copies_spin_horiz)
    copies_layout.addStretch()
    copies_layout.addWidget(label_copies2)
    copies_layout.addStretch()
    copies_layout.addWidget(parent.copies_spin_vert)
    options_layout.addLayout(copies_layout)

    left_layout.addWidget(options_box)

    # --- stats ---
    stats_box = QGroupBox("Stats")
    stats_layout = QVBoxLayout(stats_box)
    dim_group = QHBoxLayout()
    stats_label = QLabel("Output Size")
    parent.stats_label2 = QLabel("")
    dim_group.addWidget(stats_label)
    dim_group.addWidget(parent.stats_label2)
    stats_layout.addLayout(dim_group)

    width_group = QHBoxLayout()
    stats_label_width_text = QLabel("Media Width")
    parent.stats_label_width = QLabel("")
    width_group.addWidget(stats_label_width_text)
    width_group.addWidget(parent.stats_label_width)
    stats_layout.addLayout(width_group)

    left_layout.addWidget(stats_box)

    # --- Buttons ---
    controls_box = QGroupBox("Controls")
    controls_layout = QHBoxLayout(controls_box)
    parent.open_btn = QPushButton("Open SVG")
    parent.load_btn = QPushButton("Sheet")
    parent.plot_btn = QPushButton("Plot")


    controls_layout.addWidget(parent.open_btn)
    controls_layout.addWidget(parent.load_btn)
    controls_layout.addWidget(parent.plot_btn)
    left_layout.addWidget(controls_box)
    parent.plot_btn.setEnabled(False)
    parent.load_btn.setEnabled(False)


    parent.log = QPlainTextEdit("Event Log")
    parent.log.setReadOnly(True)
    parent.log.setMaximumBlockCount(1000)  # optional: limit history
    left_layout.addWidget(parent.log)

    parent.about_btn = QPushButton("About")
    left_layout.addWidget(parent.about_btn)

    # Push everything up
    left_layout.addStretch()

    # =========================
    # Graphics view (right)
    # =========================
    parent.scene = QGraphicsScene()
    parent.graphics_view = QGraphicsView(parent.scene)

    parent.graphics_view.setRenderHint(QPainter.Antialiasing)
    parent.graphics_view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    # =========================
    # Assemble main layout
    # =========================
    main_layout.addWidget(left_panel)
    main_layout.addWidget(parent.graphics_view)

    # Stretch: left ~25%, right ~75%
    main_layout.setStretch(0, 1)
    main_layout.setStretch(1, 3)

def Use_Plotter_Tool(parent):
    parent.tools_text.show()
    parent.tool_type.hide()
    parent.speed_spin.setEnabled(False)
    parent.speed_slider.setEnabled(False)
    parent.speed_slider.hide()
    parent.pressure_spin.setEnabled(False)
    parent.pressure_slider.setEnabled(False)
    parent.pressure_slider.hide()
    parent.offset_spin.setEnabled(False)

def Select_Plotter_Tool(parent):
    parent.tools_text.hide()
    parent.tool_type.show()
    parent.speed_spin.setEnabled(False)
    parent.speed_slider.setEnabled(False)
    parent.speed_slider.hide()
    parent.pressure_spin.setEnabled(False)
    parent.pressure_slider.setEnabled(False)
    parent.pressure_slider.hide()
    parent.offset_spin.setEnabled(False)

def Use_Custom_Tool(parent):
    parent.tools_text.hide()
    parent.tool_type.show()
    parent.speed_spin.setEnabled(True)
    parent.speed_slider.show()
    parent.speed_slider.setEnabled(True)
    parent.pressure_spin.setEnabled(True)
    parent.pressure_slider.show()
    parent.pressure_slider.setEnabled(True)
    parent.offset_spin.setEnabled(True)



class SettingsDialog(QDialog):
    def __init__(self, parent=None, plot_attr: object = None, ports=None):
        super().__init__(parent)
        self.plot_attr = plot_attr
        self.setWindowTitle("Settings")
        self.setFixedWidth(350)
        layout = QVBoxLayout(self)

        # --- Step Size ---
        stepsize_layout = QHBoxLayout()
        stepsize_layout.addWidget(QLabel("Step Size:"))
        self.step_size_40 = QRadioButton("0.025mm")
        self.step_size_100 = QRadioButton("0.010mm")

        # --- Convert stepsPerMM value to correct radio button
        if self.plot_attr.stepsPerMM == 40:
            self.step_size_40.setChecked(True)
        else:
            self.step_size_100.setChecked(True)

        stepsize_layout.addWidget(self.step_size_40)
        stepsize_layout.addWidget(self.step_size_100)
        layout.addLayout(stepsize_layout)

        # --- Port ---
        layout.addWidget(QLabel("Port"))
        self.port_combo = QComboBox()

        self.port_combo.addItems(ports())
        self.set_value_combo_box(str(self.plot_attr.port), self.port_combo)
        layout.addWidget(self.port_combo)

        # --- Baud ---
        layout.addWidget(QLabel("Baud rate"))
        self.baud_combo = QComboBox()
        self.baud_combo.addItems(["9600", "19200", "38400", "115200"])
        self.set_value_combo_box(str(self.plot_attr.baud), self.baud_combo)
        layout.addWidget(self.baud_combo)

        # --- OK/Cancel buttons ---
        btn_layout = QHBoxLayout()
        ok_btn = QPushButton("OK")
        cancel_btn = QPushButton("Cancel")
        btn_layout.addWidget(ok_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addLayout(btn_layout)

        # Connections
        ok_btn.clicked.connect(self.on_accept)
        cancel_btn.clicked.connect(self.reject)

    def set_value_combo_box(self, value, box):
        """
        setting the value of a QComboBox
        """
        index = box.findText(value)
        if index != -1:  # Only set if it exists
            box.setCurrentIndex(index)

    def update_plot_attr(self):
        # --- convert radio button to stepsPerMM value
        if self.step_size_40.isChecked():
            self.plot_attr.stepsPerMM = 40
        else:
            self.plot_attr.stepsPerMM = 100

        self.plot_attr.baud = int(self.baud_combo.currentText())
        self.plot_attr.port = self.port_combo.currentText()

    def on_accept(self):
        self.update_plot_attr()
        self.accept()

    def get_values(self):
        """Return dialog values"""
        return self.plot_attr


if __name__ == "__main__":
    pass
