package cn.reghao.oss.web.app.service;

import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.oss.api.dto.ObjectChannel;
import cn.reghao.oss.api.iface.OssServerService;
import cn.reghao.oss.web.account.service.UserContext;
import cn.reghao.oss.web.app.db.repository.StoreNodeRepository;
import cn.reghao.oss.web.app.db.repository.UploadChannelRepository;
import cn.reghao.oss.web.app.model.dto.UploadChannelDto;
import cn.reghao.oss.web.app.model.po.StoreNode;
import cn.reghao.oss.web.app.model.po.UploadChannel;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2024-02-23 15:14:53
 */
@Service
public class UploadChannelService {
    private final UploadChannelRepository uploadChannelRepository;
    private final StoreNodeRepository storeNodeRepository;

    public UploadChannelService(UploadChannelRepository uploadChannelRepository, StoreNodeRepository storeNodeRepository) {
        this.uploadChannelRepository = uploadChannelRepository;
        this.storeNodeRepository = storeNodeRepository;
    }

    public Result add(UploadChannelDto uploadChannelDto) {
        String domain = uploadChannelDto.getDomain();
        StoreNode storeNode = storeNodeRepository.findByDomain(domain);
        if (storeNode == null) {
            return Result.fail(String.format("store_node with domain %s not exist", domain));
        }

        int createBy = UserContext.getUser().getId();
        String channelPrefix = uploadChannelDto.getChannelPrefix();
        UploadChannel uploadChannel = uploadChannelRepository.findByPrefixAndCreateBy(channelPrefix, createBy);
        if (uploadChannel != null) {
            return Result.fail(String.format("channel_prefix %s exist", channelPrefix));
        }

        int channelId = getNextChannelId();
        uploadChannel = new UploadChannel(channelId, uploadChannelDto, createBy);
        uploadChannelRepository.save(uploadChannel);

        String name = uploadChannel.getDescription();
        long maxSize = uploadChannel.getMaxSize();
        String contentType = "video/";
        ObjectChannel channel = new ObjectChannel(name, channelPrefix, maxSize, contentType, domain);

        String host = storeNode.getIpv4Addr();
        int port = storeNode.getRpcPort();
        RemoteService<OssServerService> remoteService = new RemoteService<>();
        OssServerService ossServerService = remoteService.getService(host, port, OssServerService.class);
        ossServerService.createChannel(createBy, channel);
        return Result.success();
    }

    private int getNextChannelId() {
        int channelId = 1001;
        int userId = UserContext.getUser().getId();
        int total = uploadChannelRepository.countByCreateBy(userId);
        return channelId + total;
    }
}
