package cn.reghao.tnb.message.app.ws.service;

import cn.reghao.tnb.account.api.iface.AccountQuery;
import cn.reghao.tnb.message.api.dto.MediaProgress;
import cn.reghao.tnb.message.app.rabbit.RabbitProducer;
import cn.reghao.tnb.message.app.ws.WsConnection;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author reghao
 * @date 2024-12-02 11:36:31
 */
@Service
public class ProgressService {
    @DubboReference(check = false)
    private AccountQuery accountQuery;

    private final Map<String, MediaProgress> map = new HashMap<>();
    private final WsConnection wsConnection;
    private final RabbitProducer rabbitProducer;

    public ProgressService(WsConnection wsConnection, RabbitProducer rabbitProducer) {
        this.wsConnection = wsConnection;
        this.rabbitProducer = rabbitProducer;
    }

    public void putMediaProgress(String sessionId, MediaProgress mediaProgress) {
        map.put(sessionId, mediaProgress);
        if (mediaProgress.getEnded()) {
            persistProgress(sessionId, mediaProgress);
        }
    }

    public void removeMediaProgress(String sessionId) {
        MediaProgress mediaProgress = map.remove(sessionId);
        if (mediaProgress != null) {
            persistProgress(sessionId, mediaProgress);
        }
    }

    public void persistProgress(String sessionId, MediaProgress mediaProgress) {
        long userId = Long.parseLong(wsConnection.getUserId(sessionId));
        if (mediaProgress != null) {
            mediaProgress.setUserId(userId);
            rabbitProducer.sendMediaProgress(mediaProgress);
        }
    }
}
