#include "networkconfig.h"
#include <QDebug>
#include <QCoreApplication>
#include <QStandardPaths>

NetworkConfig& NetworkConfig::instance()
{
    static NetworkConfig instance;
    static bool initialized = false;
    if (!initialized) {
        instance.initDefaults();
        initialized = true;
    }
    return instance;
}

void NetworkConfig::resetToDefaults()
{
    initDefaults();
}

void NetworkConfig::setServerConfig(const ServerConfig& config)
{
    m_serverConfig = config;
}

void NetworkConfig::setStreamConfig(const StreamConfig& config)
{
    m_streamConfig = config;
}

void NetworkConfig::setRtmpConfig(const StreamConfig& config)
{
    m_streamConfig = config;
}

void NetworkConfig::setRecordConfig(const RecordConfig& config)
{
    m_recordConfig = config;
}

QString NetworkConfig::getRtmpUrl(const QString& streamName) const
{
    if (streamName.isEmpty()) {
        return m_streamConfig.getRtmpUrl();
    }
    return QString("rtmp://%1:%2/%3/%4")
        .arg(m_streamConfig.host)
        .arg(m_streamConfig.port)
        .arg(m_streamConfig.app)
        .arg(streamName);
}

QString NetworkConfig::getRtmpStreamUrl() const
{
    return m_streamConfig.getRtmpUrl();
}



bool NetworkConfig::isValid() const
{
    // 检查服务器配置
    if (m_serverConfig.host.isEmpty() || m_serverConfig.port <= 0 || m_serverConfig.port > 65535) {
        return false;
    }
    
    // 检查RTMP配置
    if (m_streamConfig.host.isEmpty() || m_streamConfig.port <= 0 || m_streamConfig.port > 65535) {
        return false;
    }
    
    if (m_streamConfig.app.isEmpty() || m_streamConfig.streamKey.isEmpty()) {
        return false;
    }
    
    // 检查录制配置
    if (m_recordConfig.videoBitRate <= 0 || m_recordConfig.videoFrameRate <= 0 ||
        m_recordConfig.videoQuality < 0 || m_recordConfig.videoQuality > 100 ||
        m_recordConfig.audioBitRate <= 0) {
        return false;
    }
    
    return true;
}

void NetworkConfig::initDefaults()
{
    // 服务器配置默认值
    m_serverConfig.host = "106.55.186.74";  // 使用项目中的生产服务器
    m_serverConfig.port = 8200;
    m_serverConfig.useHttps = false;
    m_serverConfig.apiPath = "/api";
    
    // 流媒体配置 (默认使用RTMP协议)
    m_streamConfig.protocol = StreamProtocol::RTSP;
    m_streamConfig.host = "106.55.186.74"; // 使用项目中的生产服务器
    m_streamConfig.port = 8554;
    m_streamConfig.app = "stream";
    m_streamConfig.streamKey = "V1";
    
    // 录制配置默认值
    m_recordConfig.outputDir = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
    if (m_recordConfig.outputDir.isEmpty()) {
        m_recordConfig.outputDir = QCoreApplication::applicationDirPath() + "/recordings";
    }
    m_recordConfig.videoBitRate = 8000000;   // 8Mbps
    m_recordConfig.videoFrameRate = 30;
    m_recordConfig.videoQuality = 100;
    m_recordConfig.audioBitRate = 128000;    // 128kbps
}
