package com.cmvr.edge.client.service.impl;

import cmvr.api.MicPhoneServiceGrpc;
import cmvr.api.MicrophoneCommand;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.cmvr.edge.client.manage.GrpcServiceManager;
import com.cmvr.edge.client.model.EdgeCommonVO;
import com.cmvr.edge.client.model.microphone.EdgeMicrophoneVolumeVO;
import com.cmvr.edge.client.service.EdgeMicrophoneService;
import com.cmvr.edge.client.utils.EdgeCommonUtil;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 边缘麦克风服务实现类
 * 用于与边缘麦克风进行gRPC通信，控制麦克风录音和状态
 * 实现了EdgeMicrophoneService接口，提供了麦克风控制的所有基本功能
 */
@Service
@RequiredArgsConstructor
public class EdgeMicrophoneServiceImpl implements EdgeMicrophoneService {
    /**
     * 日志记录器
     * 用于记录服务运行过程中的各种状态和错误信息
     */
    private static final Logger logger = LoggerFactory.getLogger(EdgeMicrophoneServiceImpl.class);

    /**
     * gRPC服务管理器
     * 用于管理和获取gRPC客户端连接
     */
    private final GrpcServiceManager grpcServiceManager;

    /**
     * 获取麦克风当前状态
     * 通过gRPC调用获取麦克风的运行状态，包括是否正在录音、音量等信息
     */
    @Override
    public String getStatus(EdgeCommonVO edgeCommonVO) {
        try {
            MicPhoneServiceGrpc.MicPhoneServiceBlockingStub stub = grpcServiceManager.getGrpcClient(edgeCommonVO.getTerminalId(), MicPhoneServiceGrpc.MicPhoneServiceBlockingStub.class);
            MicrophoneCommand.GetMicStateCommand.Request request = MicrophoneCommand.GetMicStateCommand.Request.newBuilder()
                    .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()))
                    .build();
            // 直接返回完整的 Feedback
            MicrophoneCommand.GetMicStateCommand.Feedback feedback = stub.getStatus(request);
            return JSON.toJSONString(feedback.getState());
        } catch (Exception e) {
            logger.error("获取麦克风状态失败", e);
            throw new RuntimeException("获取麦克风状态失败", e);
        }
    }

    /**
     * 开始录音
     * 通过gRPC调用开始录音，将录音保存到指定路径
     */
    @Override
    public String startRecord(EdgeCommonVO edgeCommonVO) {
        String deviceId = edgeCommonVO.getDeviceId();
        try {
            // 获取gRPC客户端存根
            MicPhoneServiceGrpc.MicPhoneServiceBlockingStub stub = grpcServiceManager.getGrpcClient(edgeCommonVO.getTerminalId(), MicPhoneServiceGrpc.MicPhoneServiceBlockingStub.class);
            String filePath = StrUtil.format("{}/{}_{}.wav", "/home/share/assets/video", deviceId, System.currentTimeMillis());

            // 构建请求消息
            MicrophoneCommand.StartMicRecordingCommand.Request request = MicrophoneCommand.StartMicRecordingCommand.Request.newBuilder()
                    .setHeader(EdgeCommonUtil.buildRequest(deviceId))
                    .setFilePath(filePath)
                    .build();

            // 发送请求
            stub.startRecord(request);
            return filePath;
        } catch (Exception e) {
            logger.error("开始录音失败", e);
            throw new RuntimeException("开始录音失败", e);
        }
    }

    /**
     * 停止录音
     * 通过gRPC调用停止麦克风的当前录音
     */
    @Override
    public String stopRecord(EdgeCommonVO edgeCommonVO) {
        try {
            // 获取gRPC客户端存根
            MicPhoneServiceGrpc.MicPhoneServiceBlockingStub stub = grpcServiceManager.getGrpcClient(edgeCommonVO.getTerminalId(), MicPhoneServiceGrpc.MicPhoneServiceBlockingStub.class);

            // 构建请求消息
            MicrophoneCommand.StopMicRecordingCommand.Request request = MicrophoneCommand.StopMicRecordingCommand.Request.newBuilder()
                    .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()))
                    .build();

            // 发送请求
            MicrophoneCommand.StopMicRecordingCommand.Feedback feedback = stub.stopRecord(request);
            return JSON.toJSONString(feedback.getHeader());
        } catch (Exception e) {
            logger.error("停止录音失败", e);
            throw new RuntimeException("停止录音失败", e);
        }
    }

    /**
     * 暂停录音
     * 通过gRPC调用暂停麦克风的当前录音
     */
    @Override
    public void pauseRecord(EdgeCommonVO edgeCommonVO) {
        try {
            // 获取gRPC客户端存根
            MicPhoneServiceGrpc.MicPhoneServiceBlockingStub stub = grpcServiceManager.getGrpcClient(edgeCommonVO.getTerminalId(), MicPhoneServiceGrpc.MicPhoneServiceBlockingStub.class);

            // 构建请求消息
            MicrophoneCommand.PauseMicRecordingCommand.Request request = MicrophoneCommand.PauseMicRecordingCommand.Request.newBuilder()
                    .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()))
                    .build();

            // 发送请求
            stub.pauseRecord(request);
        } catch (Exception e) {
            logger.error("暂停录音失败", e);
            throw new RuntimeException("暂停录音失败", e);
        }
    }

    /**
     * 恢复录音
     * 通过gRPC调用恢复麦克风之前暂停的录音
     */
    @Override
    public void resumeRecord(EdgeCommonVO edgeCommonVO) {
        try {
            // 获取gRPC客户端存根
            MicPhoneServiceGrpc.MicPhoneServiceBlockingStub stub = grpcServiceManager.getGrpcClient(edgeCommonVO.getTerminalId(), MicPhoneServiceGrpc.MicPhoneServiceBlockingStub.class);

            // 构建请求消息
            MicrophoneCommand.ResumeMicRecordingCommand.Request request = MicrophoneCommand.ResumeMicRecordingCommand.Request.newBuilder()
                    .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()))
                    .build();

            // 发送请求
            stub.resumeRecord(request);
        } catch (Exception e) {
            logger.error("恢复录音失败", e);
            throw new RuntimeException("恢复录音失败", e);
        }
    }

    /**
     * 设置麦克风音量
     * 通过gRPC调用设置麦克风的音量大小
     */
    @Override
    public void setVolume(EdgeMicrophoneVolumeVO edgeMicrophoneVolumeVO) {
        try {
            // 获取gRPC客户端存根
            MicPhoneServiceGrpc.MicPhoneServiceBlockingStub stub = grpcServiceManager.getGrpcClient(edgeMicrophoneVolumeVO.getTerminalId(), MicPhoneServiceGrpc.MicPhoneServiceBlockingStub.class);

            // 构建请求消息
            MicrophoneCommand.SetMicPhoneVolumeCommand.Request request = MicrophoneCommand.SetMicPhoneVolumeCommand.Request.newBuilder()
                    .setHeader(EdgeCommonUtil.buildRequest(edgeMicrophoneVolumeVO.getDeviceId()))
                    .setVolume(edgeMicrophoneVolumeVO.getVolume())
                    .build();

            // 发送请求
            stub.setVolume(request);
        } catch (Exception e) {
            logger.error("设置麦克风音量失败", e);
            throw new RuntimeException("设置麦克风音量失败", e);
        }
    }

    /**
     * 获取当前音量
     * 通过gRPC调用获取麦克风的当前音量大小
     */
    @Override
    public int getVolume(EdgeCommonVO edgeCommonVO) {
        try {
            // 获取gRPC客户端存根
            MicPhoneServiceGrpc.MicPhoneServiceBlockingStub stub = grpcServiceManager.getGrpcClient(edgeCommonVO.getTerminalId(), MicPhoneServiceGrpc.MicPhoneServiceBlockingStub.class);

            // 构建请求消息
            MicrophoneCommand.GetMicPhoneVolumeCommand.Request request = MicrophoneCommand.GetMicPhoneVolumeCommand.Request.newBuilder()
                    .setHeader(EdgeCommonUtil.buildRequest(edgeCommonVO.getDeviceId()))
                    .build();

            // 发送请求并获取响应
            MicrophoneCommand.GetMicPhoneVolumeCommand.Feedback response = stub.getVolume(request);
            return response.getVolume();
        } catch (Exception e) {
            logger.error("获取麦克风音量失败", e);
            throw new RuntimeException("获取麦克风音量失败", e);
        }
    }
} 