/**
 * @file MainWindow.cpp
 * @brief SkyLink Qt 地面站 - 主窗口实现
 * 
 * @author flowzl
 * @date 2026-01-19
 */

#include "MainWindow.h"
#include "GroundReceiver.h"
#include "DataLogger.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QStatusBar>
#include <QFileDialog>
#include <QDateTime>
#include <QMessageBox>
#include <iomanip>
#include <sstream>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent) {
    
    this->setWindowTitle("SkyLink 地面站 - 实时视频接收系统");
    this->setGeometry(100, 100, 1280, 800);
    
    // 初始化
    init_ui();
    init_connections();
    create_menus();
    
    // 创建接收器
    receiver_ = std::make_shared<GroundReceiver>();
    receiver_->start();
    
    // 创建记录器
    logger_ = std::make_shared<DataLogger>("./skylink_data");
    
    // 连接信号
    connect(receiver_.get(), &GroundReceiver::frameDecoded,
            this, &MainWindow::on_frame_received);
    connect(receiver_.get(), &GroundReceiver::statsUpdated,
            this, &MainWindow::on_stats_updated);
    
    statusBar()->showMessage("就绪，等待数据...");
}

MainWindow::~MainWindow() {
    if (receiver_) {
        receiver_->stop();
    }
}

void MainWindow::init_ui() {
    // 中央部件
    QWidget* central = new QWidget(this);
    this->setCentralWidget(central);
    
    QVBoxLayout* main_layout = new QVBoxLayout(central);
    
    // ========================================================================
    // 视频显示区
    // ========================================================================
    
    QGroupBox* video_group = new QGroupBox("实时视频", this);
    QVBoxLayout* video_layout = new QVBoxLayout(video_group);
    
    video_label_ = new QLabel(this);
    video_label_->setStyleSheet("background-color: #000000; border: 2px solid #333333;");
    video_label_->setMinimumSize(640, 480);
    video_label_->setAlignment(Qt::AlignCenter);
    video_label_->setText("等待视频数据...");
    video_label_->setStyleSheet(
        "background-color: #000000; "
        "color: #888888; "
        "border: 2px solid #333333; "
        "font-size: 16px;"
    );
    
    video_layout->addWidget(video_label_);
    main_layout->addWidget(video_group, 1);
    
    // ========================================================================
    // 信息和控制区
    // ========================================================================
    
    QHBoxLayout* info_control_layout = new QHBoxLayout();
    
    // GPS 信息
    QGroupBox* gps_group = new QGroupBox("GPS 信息", this);
    QVBoxLayout* gps_layout = new QVBoxLayout(gps_group);
    gps_label_ = new QLabel("纬度: -- \n经度: --\n海拔: --", this);
    gps_label_->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    gps_layout->addWidget(gps_label_);
    info_control_layout->addWidget(gps_group);
    
    // 统计信息
    QGroupBox* stats_group = new QGroupBox("实时统计", this);
    QVBoxLayout* stats_layout = new QVBoxLayout(stats_group);
    stats_label_ = new QLabel("FPS: 0\n速率: 0 KB/s\n丢包率: 0%", this);
    stats_label_->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    stats_layout->addWidget(stats_label_);
    info_control_layout->addWidget(stats_group);
    
    // 按钮组
    QGroupBox* btn_group = new QGroupBox("控制", this);
    QVBoxLayout* btn_layout = new QVBoxLayout(btn_group);
    
    save_frame_btn_ = new QPushButton("📸 保存帧", this);
    record_btn_ = new QPushButton("⏺ 开始录制", this);
    settings_btn_ = new QPushButton("⚙ 设置", this);
    
    record_btn_->setCheckable(true);
    
    btn_layout->addWidget(save_frame_btn_);
    btn_layout->addWidget(record_btn_);
    btn_layout->addWidget(settings_btn_);
    btn_layout->addStretch();
    
    info_control_layout->addWidget(btn_group);
    main_layout->addLayout(info_control_layout);
}

void MainWindow::init_connections() {
    connect(save_frame_btn_, &QPushButton::clicked,
            this, &MainWindow::on_save_frame_clicked);
    
    connect(record_btn_, &QPushButton::toggled,
            this, &MainWindow::on_record_toggled);
    
    connect(settings_btn_, &QPushButton::clicked,
            this, &MainWindow::on_settings_clicked);
}

void MainWindow::create_menus() {
    QMenuBar* menu = menuBar();
    
    // 文件菜单
    QMenu* file_menu = menu->addMenu("文件(&F)");
    QAction* exit_action = file_menu->addAction("退出");
    connect(exit_action, &QAction::triggered, this, &QWidget::close);
    
    // 帮助菜单
    QMenu* help_menu = menu->addMenu("帮助(&H)");
    QAction* about_action = help_menu->addAction("关于");
    connect(about_action, &QAction::triggered, [this]() {
        QMessageBox::information(this, "关于",
            "SkyLink 地面站 v1.0\n\n"
            "实时多平台视频传输系统\n"
            "Copyright 2026 flowzl"
        );
    });
}

void MainWindow::on_frame_received(const QImage& img, double lat, double lon, double alt) {
    current_image_ = img;
    current_lat_ = lat;
    current_lon_ = lon;
    current_alt_ = alt;
    
    // 显示图像
    if (!img.isNull()) {
        QPixmap pixmap = QPixmap::fromImage(img);
        int w = video_label_->width();
        int h = video_label_->height();
        video_label_->setPixmap(pixmap.scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    }
    
    // 更新 GPS 标签
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(6);
    oss << "纬度: " << lat << "°\n";
    oss << "经度: " << lon << "°\n";
    oss << "海拔: " << std::fixed << std::setprecision(1) << alt << " m";
    gps_label_->setText(QString::fromStdString(oss.str()));
    
    // 如果正在录制，保存帧
    if (is_recording_ && logger_) {
        logger_->save_frame(img, lat, lon, alt);
    }
}

void MainWindow::on_stats_updated(int fps, int kbs) {
    std::ostringstream oss;
    oss << "FPS: " << fps << "\n";
    oss << "速率: " << kbs << " KB/s\n";
    oss << "丢包率: " << "计算中..." << "%";
    stats_label_->setText(QString::fromStdString(oss.str()));
}

void MainWindow::on_save_frame_clicked() {
    if (current_image_.isNull()) {
        QMessageBox::warning(this, "警告", "还没有接收到图像");
        return;
    }
    
    QString file = QFileDialog::getSaveFileName(this,
        "保存图像", QString(),
        "JPEG Image (*.jpg);;PNG Image (*.png)");
    
    if (!file.isEmpty()) {
        current_image_.save(file);
        statusBar()->showMessage("图像已保存: " + file);
    }
}

void MainWindow::on_record_toggled(bool checked) {
    is_recording_ = checked;
    
    if (checked) {
        record_btn_->setText("⏹ 停止录制");
        statusBar()->showMessage("开始录制...");
    } else {
        record_btn_->setText("⏺ 开始录制");
        statusBar()->showMessage("录制已停止");
    }
}

void MainWindow::on_settings_clicked() {
    QMessageBox::information(this, "设置",
        "设置功能开发中...\n\n"
        "支持的设置项：\n"
        "- UDP 绑定端口\n"
        "- 视频保存路径\n"
        "- 丢包检测\n"
        "- GPS 地图显示"
    );
}
