#include "rtsp_manager.hpp"
#include "logger.hpp"
#include <iostream>
#include <mutex>

// 静态变量定义
GMainLoop *RTSPManager::loop = nullptr;
GMainContext *RTSPManager::main_context = nullptr; // 新增
GstRTSPServer *RTSPManager::server = nullptr;
std::unordered_map<std::string, bool> RTSPManager::streaming_status; // 播放状态表

// 保存已挂载的 factory，方便卸载时找到并释放
static std::unordered_map<std::string, GstRTSPMediaFactory *> mounted_factories;
static std::mutex mounted_factories_mutex;

void RTSPManager::init()
{
    gst_init(nullptr, nullptr);
    LOG_INFO("[RTSP] GStreamer initialized.");
}

GstRTSPMediaFactory *RTSPManager::create_media_factory(const Camera &cam)
{
    std::string launch_str =
        "( v4l2src device=" + cam.device +
        " ! video/x-raw,format=NV12,width=" + std::to_string(cam.width) +
        ",height=" + std::to_string(cam.height) +
        ",framerate=" + std::to_string(cam.fps) + "/1"
                                                  " ! videoconvert ! queue ! mpph264enc ! rtph264pay name=pay0 pt=96 )";

    GstRTSPMediaFactory *factory = gst_rtsp_media_factory_new();
    gst_rtsp_media_factory_set_launch(factory, launch_str.c_str());
    gst_rtsp_media_factory_set_shared(factory, TRUE);

    return factory;
}

void RTSPManager::start(const std::vector<Camera> &cameras)
{
    server = gst_rtsp_server_new();
    gst_rtsp_server_set_service(server, "8554");

    // 不在启动时挂载摄像头，由调度指令控制推流
    loop = g_main_loop_new(nullptr, FALSE);
    main_context = g_main_loop_get_context(loop); // 保存 context

    gst_rtsp_server_attach(server, nullptr);

    LOG_INFO("[RTSP] Server running on rtsp://localhost:8554");
    g_main_loop_run(loop);

    if (server)
    {
        g_object_unref(server);
        server = nullptr;
    }
    if (loop)
    {
        g_main_loop_unref(loop);
        loop = nullptr;
    }
    LOG_INFO("[RTSP] Server stopped.");
}

// --- 主线程挂载函数 ---
static gboolean mount_camera_in_main(gpointer data)
{
    Camera *cam = static_cast<Camera *>(data);
    if (!cam)
        return G_SOURCE_REMOVE;
    if (!RTSPManager::server)
    {
        delete cam;
        return G_SOURCE_REMOVE;
    }

    GstRTSPMountPoints *mounts = gst_rtsp_server_get_mount_points(RTSPManager::server);
    if (!mounts)
    {
        delete cam;
        return G_SOURCE_REMOVE;
    }

    std::string mount_point = "/" + cam->name;
    GstRTSPMediaFactory *factory = RTSPManager::create_media_factory(*cam);
    if (!factory)
    {
        g_object_unref(mounts);
        delete cam;
        return G_SOURCE_REMOVE;
    }

    gst_rtsp_mount_points_add_factory(mounts, mount_point.c_str(), factory);
    g_object_unref(mounts);

    {
        std::lock_guard<std::mutex> lock(mounted_factories_mutex);
        mounted_factories[cam->name] = factory;
        RTSPManager::streaming_status[cam->name] = true;
    }

    LOG_INFO("[RTSP] Camera '" + cam->name + "' mounted at rtsp://localhost:8554" + mount_point);
    delete cam;
    return G_SOURCE_REMOVE;
}

// --- 主线程卸载函数 ---
static gboolean unmount_camera_in_main(gpointer data)
{
    Camera *cam = static_cast<Camera *>(data);
    if (!cam)
        return G_SOURCE_REMOVE;
    if (!RTSPManager::server)
    {
        delete cam;
        return G_SOURCE_REMOVE;
    }

    GstRTSPMountPoints *mounts = gst_rtsp_server_get_mount_points(RTSPManager::server);
    if (!mounts)
    {
        delete cam;
        return G_SOURCE_REMOVE;
    }

    std::string mount_point = "/" + cam->name;
    gst_rtsp_mount_points_remove_factory(mounts, mount_point.c_str());
    g_object_unref(mounts);

    {
        std::lock_guard<std::mutex> lock(mounted_factories_mutex);
        auto it = mounted_factories.find(cam->name);
        if (it != mounted_factories.end())
        {
            GstRTSPMediaFactory *factory = it->second;
            if (factory)
                g_object_unref(factory);
            mounted_factories.erase(it);
        }
        RTSPManager::streaming_status[cam->name] = false;
    }

    LOG_INFO("[RTSP] Camera '" + cam->name + "' unmounted.");
    delete cam;
    return G_SOURCE_REMOVE;
}

// 公共接口：挂载摄像头（线程安全）
void RTSPManager::mount_camera(const Camera &cam)
{
    Camera *camCopy = new Camera(cam);
    g_main_context_invoke(main_context, [](gpointer data) -> gboolean
                          { return mount_camera_in_main(data); }, camCopy);
}

// 公共接口：卸载摄像头（线程安全）
void RTSPManager::unmount_camera(const Camera &cam)
{
    Camera *camCopy = new Camera(cam);
    g_main_context_invoke(main_context, [](gpointer data) -> gboolean
                          { return unmount_camera_in_main(data); }, camCopy);
}

// 查询播放状态
bool RTSPManager::is_streaming(const std::string &cam_name)
{
    std::lock_guard<std::mutex> lock(mounted_factories_mutex);
    auto it = streaming_status.find(cam_name);
    return it != streaming_status.end() ? it->second : false;
}

void RTSPManager::stop()
{
    if (loop)
    {
        g_main_context_invoke(main_context, [](gpointer data) -> gboolean
                              {
            GMainLoop *loop = static_cast<GMainLoop *>(data);
            g_main_loop_quit(loop);
            return G_SOURCE_REMOVE; }, loop);
    }
}
