#include "capture_abstract_capturer.h"
#include "../base/logger.h"
#include <chrono>

namespace av {
namespace capture {

AbstractCapturer::AbstractCapturer() {
    stats_.startTime = std::chrono::steady_clock::now();
    lastFrameTime_ = std::chrono::steady_clock::now();
    lastFpsCalcTime_ = std::chrono::steady_clock::now();
    AV_LOGGER_DEBUG("创建抽象采集器");
}

AbstractCapturer::~AbstractCapturer() {
    AV_LOGGER_DEBUG("抽象采集器已销毁");
}

void AbstractCapturer::setState(CapturerState state) {
    CapturerState oldState = state_.exchange(state);
    if (oldState != state) {
        AV_LOGGER_INFOF("采集器状态变更: {} -> {}", 
                       static_cast<int>(oldState), static_cast<int>(state));
    }
}

void AbstractCapturer::onFrameCaptured(const AVFramePtr& frame) {
    if (!frame) {
        AV_LOGGER_WARNING("采集到空帧");
        return;
    }
    
    auto now = std::chrono::steady_clock::now();
    double captureTime = std::chrono::duration<double, std::milli>(now - lastFrameTime_).count();
    lastFrameTime_ = now;
    
    // 计算数据大小
    size_t dataSize = 0;
    if (frame->data[0]) {
        for (int i = 0; i < AV_NUM_DATA_POINTERS && frame->data[i]; ++i) {
            dataSize += frame->linesize[i] * frame->height;
        }
    }
    
    updateStats(true, captureTime, dataSize);
    calculateFPS();
    
    if (frameCallback_) {
        frameCallback_(frame);
    }
}

void AbstractCapturer::onError(ErrorCode error, const std::string& message) {
    updateStats(false, 0.0);
    
    AV_LOGGER_ERRORF("采集器错误: {} - {}", static_cast<int>(error), message);
    
    if (errorCallback_) {
        errorCallback_(error, message);
    }
}

void AbstractCapturer::updateStats(bool success, double captureTime, size_t dataSize) {
    std::lock_guard<std::mutex> lock(statsMutex_);
    
    if (success) {
        stats_.capturedFrames++;
        stats_.totalBytes += dataSize;
        
        // 更新平均采集时间
        if (stats_.capturedFrames == 1) {
            stats_.avgCaptureTime = captureTime;
        } else {
            stats_.avgCaptureTime = (stats_.avgCaptureTime * (stats_.capturedFrames - 1) + captureTime) / stats_.capturedFrames;
        }
    } else {
        stats_.errorCount++;
    }
}

void AbstractCapturer::calculateFPS() {
    frameCountForFps_++;
    
    auto now = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration<double>(now - lastFpsCalcTime_).count();
    
    // 每秒计算一次FPS
    if (elapsed >= 1.0) {
        std::lock_guard<std::mutex> lock(statsMutex_);
        stats_.fps = frameCountForFps_ / elapsed;
        
        frameCountForFps_ = 0;
        lastFpsCalcTime_ = now;
    }
}

CapturerStats AbstractCapturer::getStats() const {
    std::lock_guard<std::mutex> lock(statsMutex_);
    return stats_;
}

void AbstractCapturer::resetStats() {
    std::lock_guard<std::mutex> lock(statsMutex_);
    stats_ = CapturerStats{};
    stats_.startTime = std::chrono::steady_clock::now();
    
    frameCountForFps_ = 0;
    lastFpsCalcTime_ = std::chrono::steady_clock::now();
    
    AV_LOGGER_DEBUG("采集器统计信息已重置");
}

// CapturerFactory 实现
bool CapturerFactory::isCapturerSupported(CapturerType type) {
    switch (type) {
        case CapturerType::VIDEO_CAMERA:
        case CapturerType::VIDEO_SCREEN:
        case CapturerType::AUDIO_MIC:
        case CapturerType::AUDIO_SYSTEM:
        case CapturerType::AUDIO_LOOPBACK:
            return true;
        default:
            return false;
    }
}

std::vector<CapturerType> CapturerFactory::getAvailableCapturerTypes() {
    std::vector<CapturerType> types;
    
    // 检查各种采集器类型的可用性
    if (isCapturerSupported(CapturerType::VIDEO_CAMERA)) {
        types.push_back(CapturerType::VIDEO_CAMERA);
    }
    
    if (isCapturerSupported(CapturerType::VIDEO_SCREEN)) {
        types.push_back(CapturerType::VIDEO_SCREEN);
    }
    
    if (isCapturerSupported(CapturerType::AUDIO_MIC)) {
        types.push_back(CapturerType::AUDIO_MIC);
    }
    
    if (isCapturerSupported(CapturerType::AUDIO_SYSTEM)) {
        types.push_back(CapturerType::AUDIO_SYSTEM);
    }
    
    if (isCapturerSupported(CapturerType::AUDIO_LOOPBACK)) {
        types.push_back(CapturerType::AUDIO_LOOPBACK);
    }
    
    return types;
}

std::string CapturerFactory::getCapturerTypeName(CapturerType type) {
    switch (type) {
        case CapturerType::VIDEO_CAMERA:
            return "摄像头";
        case CapturerType::VIDEO_SCREEN:
            return "屏幕录制";
        case CapturerType::AUDIO_MIC:
            return "麦克风";
        case CapturerType::AUDIO_SYSTEM:
            return "系统音频";
        case CapturerType::AUDIO_LOOPBACK:
            return "音频回环";
        default:
            return "未知";
    }
}

} // namespace capture
} // namespace av