"""Week 14 - Qt desktop client for the MKR + IoT Carrier.
Live sensor dashboard, choose what the board display shows, build/run LED scripts.
pip install PySide6
python fab_client.py
"""
import csv
import json
import re
import sys
from datetime import datetime
from pathlib import Path

from PySide6.QtCore import QByteArray, Qt, QTimer, QUrl
from PySide6.QtGui import QColor
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
from PySide6.QtWidgets import (QApplication, QCheckBox, QColorDialog, QComboBox, QGridLayout,
                               QGroupBox, QHBoxLayout, QLabel, QLineEdit, QListWidget,
                               QPlainTextEdit, QPushButton, QSlider, QSpinBox, QVBoxLayout, QWidget)

SENSORS = [("temperature", "Temperature", "{:.1f} °C"),
           ("humidity", "Humidity", "{:.1f} %"),
           ("pressure", "Pressure", "{:.1f} hPa"),
           ("light", "Light", "{}"),
           ("ax", "Accel X", "{:.2f} g"),
           ("ay", "Accel Y", "{:.2f} g"),
           ("az", "Accel Z", "{:.2f} g")]
CSV_PATH = Path.home() / "carrier_sensors.csv"


class App(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Carrier Interface")
        self.nam = QNetworkAccessManager(self)
        self.colour = QColor(255, 0, 0)
        self.last_state_key = None

        # connection
        self.ip = QLineEdit("192.168.0.25")
        self.refresh_btn = QPushButton("Refresh files")
        self.show_all = QCheckBox("show all SD files (debug)")

        # sensor dashboard
        self.value_labels = {}
        grid = QGridLayout()
        for i, (key, name, _fmt) in enumerate(SENSORS):
            grid.addWidget(QLabel(name + ":"), i // 4, (i % 4) * 2)
            lbl = QLabel("--")
            lbl.setStyleSheet("font-weight: bold; font-size: 16px;")
            self.value_labels[key] = lbl
            grid.addWidget(lbl, i // 4, (i % 4) * 2 + 1)
        self.show_combo = QComboBox()
        self.show_combo.addItems(["none", "temperature", "humidity", "pressure", "light"])
        self.record = QCheckBox(f"record to {CSV_PATH.name}")
        row = QHBoxLayout()
        row.addWidget(QLabel("Show on board display:"))
        row.addWidget(self.show_combo)
        row.addWidget(self.record)
        row.addStretch()
        box = QGroupBox("Board sensors")
        bl = QVBoxLayout(box)
        bl.addLayout(grid)
        bl.addLayout(row)

        # file list + editor
        self.files = QListWidget()
        self.editor = QPlainTextEdit()
        self.editor.setPlaceholderText("Script appears here. Edit it, or build one with the controls below.")

        # builder row
        self.text_in = QLineEdit()
        self.text_in.setPlaceholderText("screen text")
        self.colour_btn = QPushButton("Colour")
        self.wait = QSpinBox(minimum=50, maximum=60000, value=500, singleStep=100, suffix=" ms")
        self.add_btn = QPushButton("Add step")
        self.clear_btn = QPushButton("Clear")
        self.loop = QCheckBox("loop")

        # action row
        self.run_sd_btn = QPushButton("Run selected (SD)")
        self.run_mem_btn = QPushButton("Run editor (no SD)")
        self.save_name = QLineEdit("MYSCRIPT")
        self.save_name.setMaximumWidth(110)
        self.save_btn = QPushButton("Save editor to SD")
        self.pause_btn = QPushButton("Pause / Resume")
        self.stop_btn = QPushButton("Stop")

        # brightness
        self.bright = QSlider(Qt.Horizontal, minimum=0, maximum=100, value=100)
        self.bright_label = QLabel("100%")

        # log + status
        self.log = QPlainTextEdit(readOnly=True)
        self.log.setMaximumHeight(90)
        self.status = QLabel("Status: unknown")

        top = QHBoxLayout()
        top.addWidget(QLabel("Board IP:"))
        top.addWidget(self.ip)
        top.addWidget(self.refresh_btn)
        top.addWidget(self.show_all)

        mid = QHBoxLayout()
        mid.addWidget(self.files, 1)
        mid.addWidget(self.editor, 2)

        build = QHBoxLayout()
        for w in (self.text_in, self.colour_btn, self.wait, self.add_btn, self.clear_btn, self.loop):
            build.addWidget(w)

        act = QHBoxLayout()
        for w in (self.run_sd_btn, self.run_mem_btn, self.save_name, self.save_btn,
                  self.pause_btn, self.stop_btn):
            act.addWidget(w)

        br = QHBoxLayout()
        br.addWidget(QLabel("LED brightness:"))
        br.addWidget(self.bright, 1)
        br.addWidget(self.bright_label)

        lay = QVBoxLayout(self)
        lay.addLayout(top)
        lay.addWidget(box)
        for l in (mid, build, act, br):
            lay.addLayout(l)
        lay.addWidget(QLabel("Events:"))
        lay.addWidget(self.log)
        lay.addWidget(self.status)

        self.update_colour_button()
        self.refresh_btn.clicked.connect(self.load_files)
        self.files.currentTextChanged.connect(self.load_preview)
        self.colour_btn.clicked.connect(self.pick_colour)
        self.add_btn.clicked.connect(self.add_step)
        self.clear_btn.clicked.connect(self.editor.clear)
        self.run_sd_btn.clicked.connect(self.run_selected)
        self.run_mem_btn.clicked.connect(self.run_editor)
        self.save_btn.clicked.connect(self.save_editor)
        self.pause_btn.clicked.connect(lambda: self.call("POST", "/pause"))
        self.stop_btn.clicked.connect(lambda: self.call("POST", "/stop"))
        self.show_combo.activated.connect(
            lambda _i: self.call("POST", f"/show?what={self.show_combo.currentText()}"))
        self.bright.valueChanged.connect(lambda v: self.bright_label.setText(f"{v}%"))
        self.bright.sliderReleased.connect(
            lambda: self.call("POST", f"/brightness?v={self.bright.value()}"))

        self.timer = QTimer(self, interval=1000)
        self.timer.timeout.connect(self.poll)
        self.timer.start()

    # --- non-blocking HTTP helper ---
    def call(self, method, path, cb=None, body=None):
        req = QNetworkRequest(QUrl(f"http://{self.ip.text().strip()}{path}"))
        req.setTransferTimeout(3000)
        if method == "GET":
            reply = self.nam.get(req)
        else:
            req.setHeader(QNetworkRequest.ContentTypeHeader, "text/plain")
            reply = self.nam.post(req, QByteArray((body or "").encode()))
        reply.finished.connect(lambda r=reply: self.done(r, cb))

    def done(self, reply: QNetworkReply, cb):
        text = bytes(reply.readAll()).decode(errors="replace")
        code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        if code is not None and code >= 400:
            self.status.setText(f"Board said {code}: {text}")
        elif reply.error() != QNetworkReply.NoError:
            self.status.setText(f"Status: offline ({reply.errorString()})")
        elif cb:
            cb(text)
        reply.deleteLater()

    def log_line(self, msg):
        self.log.appendPlainText(f"{datetime.now():%H:%M:%S}  {msg}")

    # --- builder ---
    def update_colour_button(self):
        c = self.colour
        fg = "black" if c.lightness() > 128 else "white"
        self.colour_btn.setStyleSheet(f"background-color: {c.name()}; color: {fg};")

    def pick_colour(self):
        c = QColorDialog.getColor(self.colour, self)
        if c.isValid():
            self.colour = c
            self.update_colour_button()

    def add_step(self):
        lines = []
        t = self.text_in.text().strip()
        if t:
            lines.append(f"TEXT {t}")
        c = self.colour
        lines.append(f"COLOR {c.red()} {c.green()} {c.blue()}")
        lines.append(f"WAIT {self.wait.value()}")
        self.editor.appendPlainText("\n".join(lines))

    def script_text(self):
        s = self.editor.toPlainText().strip()
        if self.loop.isChecked() and not s.endswith("LOOP"):
            s += "\nLOOP"
        return s + "\n"

    # --- actions ---
    def load_files(self):
        def fill(text):
            self.files.clear()
            self.files.addItems([n for n in text.splitlines() if n.strip()])
            if not self.files.count():
                self.status.setText("Status: board answered but found no files")
        path = "/files?all=1" if self.show_all.isChecked() else "/files"
        self.call("GET", path, fill)

    def load_preview(self, name):
        if name and not name.endswith("/"):
            self.call("GET", f"/file?name={name}", self.editor.setPlainText)

    def run_selected(self):
        item = self.files.currentItem()
        if item:
            self.call("POST", f"/run?name={item.text()}")

    def run_editor(self):
        self.call("POST", "/runtext", body=self.script_text())

    def save_editor(self):
        base = re.sub(r"[^A-Za-z0-9]", "", self.save_name.text()).upper()[:8] or "MYSCRIPT"
        self.save_name.setText(base)
        self.call("POST", f"/save?name={base}.FAB", self.after_save, body=self.script_text())

    def after_save(self, _text):
        self.status.setText("Status: saved to SD")
        self.load_files()

    # --- polling ---
    def poll(self):
        self.call("GET", "/sensors", self.show_sensors)
        self.call("GET", "/status", self.show_status)

    def show_sensors(self, text):
        s = json.loads(text)
        for key, _name, fmt in SENSORS:
            if key in s:
                self.value_labels[key].setText(fmt.format(s[key]))
        if self.record.isChecked():
            new = not CSV_PATH.exists()
            with CSV_PATH.open("a", newline="") as f:
                w = csv.writer(f)
                if new:
                    w.writerow(["time"] + [k for k, _n, _f in SENSORS])
                w.writerow([datetime.now().isoformat(timespec="seconds")] + [s.get(k) for k, _n, _f in SENSORS])

    def show_status(self, text):
        s = json.loads(text)
        sd = "SD ok" if s.get("sd") else "NO SD"
        state = "paused" if s.get("paused") else s["state"]
        self.status.setText(f"Status: {state}  file={s['file']}  last stop={s['last']}  [{sd}]")

        key = (s["state"], s.get("paused"), s["file"], s["last"])
        if self.last_state_key is not None and key != self.last_state_key:
            self.log_line(f"state: {state}  file={s['file']}  last stop={s['last']}")
        self.last_state_key = key

        # keep controls in sync with the board
        if not self.bright.isSliderDown() and self.bright.value() != s["brightness"]:
            self.bright.blockSignals(True)
            self.bright.setValue(s["brightness"])
            self.bright.blockSignals(False)
            self.bright_label.setText(f"{s['brightness']}%")
        if self.show_combo.currentText() != s["show"] and not self.show_combo.view().isVisible():
            self.show_combo.setCurrentText(s["show"])


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = App()
    w.resize(980, 700)
    w.show()
    sys.exit(app.exec())
