package cn.reghao.oss.console.app.rpc;

import cn.reghao.oss.console.app.model.po.StoreNode;
import cn.reghao.oss.console.app.service.UploadChannelService;
import cn.reghao.oss.console.util.AuthKeyContext;
import cn.reghao.oss.storeapi.dto.media.AudioInfo;
import cn.reghao.oss.storeapi.dto.media.ConvertedImageInfo;
import cn.reghao.oss.storeapi.dto.media.ImageInfo;
import cn.reghao.oss.storeapi.dto.media.VideoInfo;
import cn.reghao.oss.storeapi.iface.MediaService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2024-03-07 09:47:12
 */
@Service
public class MediaRpcService {
    private final UploadChannelService uploadChannelService;

    public MediaRpcService(UploadChannelService uploadChannelService) {
        this.uploadChannelService = uploadChannelService;
    }

    public VideoInfo getVideoInfo(int channelId, String videoFileId) throws Exception {
        MediaService mediaService = getMediaService(channelId);
        return mediaService.getVideoInfo(videoFileId);
    }

    public List<ImageInfo> getImagesInfo(int channelId, List<String> imageFileIds) throws Exception {
        MediaService mediaService = getMediaService(channelId);
        return mediaService.getImagesInfo(imageFileIds);
    }

    public List<ConvertedImageInfo> getWebpInfo(int channelId, List<String> imageFileIds) throws Exception {
        int loginUser = AuthKeyContext.getUser();
        MediaService mediaService = getMediaService(channelId);
        return mediaService.getWebpInfo(loginUser, imageFileIds);
    }

    public AudioInfo getAudioInfo(int channelId, String audioFileId) throws Exception {
        MediaService mediaService = getMediaService(channelId);
        return mediaService.getAudioInfo(audioFileId);
    }

    private MediaService getMediaService(int channelId) throws Exception {
        StoreNode storeNode = uploadChannelService.getStoreNodeByChannelId(channelId);
        if (storeNode == null) {
            String errMsg = String.format("channel_id %s not associate with any store_node", channelId);
            throw new Exception(errMsg);
        }

        RemoteService<MediaService> remoteService = new RemoteService<>();
        String host = storeNode.getNodeAddr();
        int port = storeNode.getRpcPort();
        return remoteService.getService(host, port, MediaService.class);
    }
}
