import os
import json
from PyQt6.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout, 
                             QPushButton, QLabel, QFrame)
from PyQt6.QtCore import Qt, QTimer

def get_gcode_dir():
    config_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.json")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            config = json.load(f)
            return config.get("GCODE_DIR", "/home/lhye200/.octoprint/uploads")
    except:
        return "/home/lhye200/.octoprint/uploads"

GCODE_DIR = get_gcode_dir()

class StatusPage(QWidget):
    def __init__(self, api_client, parent=None):
        super().__init__(parent)
        self.api_client = api_client
        self.current_file = None
        self.init_ui()
        
        # 定时器刷新状态
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_status)
        self.timer.start(2000)
        self.update_status()

    def init_ui(self):
        main_layout = QHBoxLayout(self)
        
        # --- 左侧：状态与控制 ---
        self.left_frame = QFrame()
        self.left_frame.setStyleSheet("background-color: #444444; border-radius: 10px;")
        left_layout = QVBoxLayout(self.left_frame)
        
        self.lbl_status = QLabel("状态: 未知")
        self.lbl_status.setStyleSheet("color: white; font-size: 24px; border: none;")
        self.lbl_job = QLabel("文件: 无")
        self.lbl_job.setStyleSheet("color: white; font-size: 18px; border: none;")
        self.lbl_progress = QLabel("进度: 0%")
        self.lbl_progress.setStyleSheet("color: white; font-size: 18px; border: none;")
        
        left_layout.addWidget(self.lbl_status)
        left_layout.addWidget(self.lbl_job)
        left_layout.addWidget(self.lbl_progress)
        left_layout.addStretch()
        
        btn_layout = QHBoxLayout()
        self.btn_pause = QPushButton("暂停/恢复")
        self.btn_pause.setStyleSheet(self.btn_style())
        self.btn_pause.clicked.connect(self.toggle_pause)
        self.btn_pause.setMinimumHeight(60)
        
        self.btn_stop = QPushButton("停止")
        self.btn_stop.setStyleSheet(self.btn_style())
        self.btn_stop.clicked.connect(self.stop_print)
        self.btn_stop.setMinimumHeight(60)
        
        btn_layout.addWidget(self.btn_pause)
        btn_layout.addWidget(self.btn_stop)
        left_layout.addLayout(btn_layout)

        # --- 右侧：预览 ---
        self.right_frame = QFrame()
        self.right_frame.setStyleSheet("background-color: #444444; border-radius: 10px;")
        right_layout = QVBoxLayout(self.right_frame)
        self.lbl_preview = QLabel("暂无预览...")
        self.lbl_preview.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.lbl_preview.setStyleSheet("color: white; font-size: 18px; border: none;")
        right_layout.addWidget(self.lbl_preview)
        
        main_layout.addWidget(self.left_frame, 1)
        main_layout.addWidget(self.right_frame, 1)

    def btn_style(self):
        return """
            QPushButton {
                background-color: #555555;
                color: white;
                border: 2px solid #666666;
                border-radius: 5px;
                font-size: 20px;
                padding: 10px;
            }
            QPushButton:pressed {
                background-color: #333333;
                border: 2px solid #4CAF50;
            }
        """

    def toggle_pause(self):
        self.api_client.pause_print()

    def stop_print(self):
        self.api_client.stop_print()

    def update_status(self):
        data = self.api_client.get_status()
        if data:
            status = data.get("status", {})
            job = data.get("job", {})

            state_str = status.get("state", {}).get("text", "离线")
            self.lbl_status.setText(f"状态: {state_str}")

            file_name_node = job.get("job", {}).get("file", {})
            file_name = file_name_node.get("name") if file_name_node else "无"
            if not file_name: 
                file_name = "无"
            self.lbl_job.setText(f"文件: {file_name}")

            progress_node = job.get("progress", {})
            progress = progress_node.get("completion") if progress_node else 0
            if progress is None: progress = 0
            self.lbl_progress.setText(f"进度: {progress:.1f}%")

            if file_name and file_name != "无" and file_name != self.current_file:
                self.current_file = file_name
                self.render_preview(file_name)

    def render_preview(self, filename):
        filepath = os.path.join(GCODE_DIR, filename)
        if not os.path.exists(filepath):
            self.lbl_preview.setText(f"未找到对应的GCode文件:\n{filename}")
            return
        
        self.lbl_preview.setText(f"预览渲染成功:\n{filename}")
