package cn.reghao.tnb.content.app.vod.service;

import cn.reghao.file.api.iface.OssService;
import cn.reghao.tnb.content.app.vod.model.dto.VideoUrlDto;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.vod.db.repository.VideoRepository;
import cn.reghao.tnb.content.app.vod.model.po.VideoPost;
import cn.reghao.tnb.content.app.vod.model.vo.DownloadUrl;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2022-08-05 13:49:28
 */
@Slf4j
@Service
public class VideoService {
    @DubboReference(check = false)
    private OssService ossService;

    private final VideoRepository videoRepository;

    public VideoService(VideoRepository videoRepository) {
        this.videoRepository = videoRepository;
    }

    public void thumbVideo(String videoId) {
        videoRepository.updateIncrView(videoId);
    }

    public String getShareLink(String videoId) {
        String shortUrl = String.format("/s/%s", videoId);
        return shortUrl;
    }

    public DownloadUrl downloadVideo(String videoId) {
        long userId = UserContext.getUserId();
        VideoPost videoPost = videoRepository.getVideoPost(videoId);
        if (videoPost == null) {
            return null;
        }

        List<VideoUrlDto> list = videoRepository.getVideoUrls(videoId);
        for (VideoUrlDto videoUrlDto : list) {
            try {
                int channelCode = videoUrlDto.getChannelCode();
                String videoFileId = videoUrlDto.getObjectId();
                String signedUrl = ossService.getSignedUrl(videoFileId, null);
                return new DownloadUrl(signedUrl, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
