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

namespace av {
namespace recorder {

AbstractRecorder::AbstractRecorder(MediaType mediaType)
    : mediaType_(mediaType)
    , state_(RecorderState::IDLE)
    , frameCountForFps_(0) {
    stats_.startTime = std::chrono::steady_clock::now();
    lastFrameTime_ = std::chrono::steady_clock::now();
    lastFpsCalcTime_ = std::chrono::steady_clock::now();
}

AbstractRecorder::~AbstractRecorder() {
    close();
}

RecorderStats AbstractRecorder::getStats() const {
    std::lock_guard<std::mutex> lock(statsMutex_);
    auto stats = stats_;
    
    // 计算录制时长
    if (state_.load() == RecorderState::RECORDING || 
        state_.load() == RecorderState::PAUSED ||
        state_.load() == RecorderState::STOPPED) {
        auto now = std::chrono::steady_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - stats_.startTime);
        stats.recordingTime = duration.count() / 1000.0;
    }
    
    return stats;
}

void AbstractRecorder::resetStats() {
    std::lock_guard<std::mutex> lock(statsMutex_);
    stats_ = RecorderStats{};
    stats_.startTime = std::chrono::steady_clock::now();
    frameCountForFps_ = 0;
    lastFrameTime_ = std::chrono::steady_clock::now();
    lastFpsCalcTime_ = std::chrono::steady_clock::now();
}

void AbstractRecorder::setState(RecorderState state) {
    RecorderState oldState = state_.exchange(state);
    
    if (oldState != state) {
        AV_LOGGER_INFOF("Recorder state changed: {} -> {}", 
                static_cast<int>(oldState), static_cast<int>(state));
        
        if (stateCallback_) {
            stateCallback_(state);
        }
        
        // 状态变化时重置统计开始时间
        if (state == RecorderState::RECORDING) {
            std::lock_guard<std::mutex> lock(statsMutex_);
            stats_.startTime = std::chrono::steady_clock::now();
        }
    }
}

void AbstractRecorder::reportError(ErrorCode error, const std::string& message) {
    setState(RecorderState::ERROR);
    
    {
        std::lock_guard<std::mutex> lock(statsMutex_);
        stats_.errorCount++;
    }
    
    AV_LOGGER_ERRORF("Recorder error: {} - {}", static_cast<int>(error), message);
    
    if (errorCallback_) {
        errorCallback_(error, message);
    }
}

void AbstractRecorder::updateStats(bool success, uint64_t bytes) {
    std::lock_guard<std::mutex> lock(statsMutex_);
    
    if (success) {
        stats_.recordedFrames++;
        stats_.totalBytes += bytes;
        frameCountForFps_++;
    } else {
        stats_.droppedFrames++;
    }
    
    // 定期计算帧率
    auto now = std::chrono::steady_clock::now();
    auto timeSinceLastCalc = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastFpsCalcTime_);
    
    if (timeSinceLastCalc.count() >= 1000) { // 每秒计算一次
        calculateFrameRate();
    }
}

void AbstractRecorder::calculateFrameRate() {
    auto now = std::chrono::steady_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastFpsCalcTime_);
    
    if (duration.count() > 0) {
        stats_.avgFrameRate = (frameCountForFps_ * 1000.0) / duration.count();
        frameCountForFps_ = 0;
        lastFpsCalcTime_ = now;
    }
}

// RecorderFactory 实现
std::unique_ptr<AbstractRecorder> RecorderFactory::createRecorder(MediaType mediaType) {
    // 这里将在具体的录制器实现中完成
    // 目前返回nullptr，待后续实现具体的录制器类
    return nullptr;
}

bool RecorderFactory::isRecorderSupported(MediaType mediaType) {
    switch (mediaType) {
        case MediaType::AUDIO:
        case MediaType::VIDEO:
            return true;
        default:
            return false;
    }
}

std::vector<MediaType> RecorderFactory::getSupportedMediaTypes() {
    return {MediaType::AUDIO, MediaType::VIDEO};
}

} // namespace recorder
} // namespace av