package cn.reghao.oss.store.rpc;

import cn.reghao.oss.storeapi.constant.ObjectScope;
import cn.reghao.oss.store.service.FileStoreService;
import cn.reghao.oss.store.service.ObjectNameService;
import cn.reghao.oss.store.service.StoreLocalService;
import cn.reghao.oss.store.util.JwtUtil;
import cn.reghao.oss.storeapi.constant.ChannelAction;
import cn.reghao.oss.storeapi.dto.*;
import cn.reghao.oss.storeapi.iface.StoreService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2023-08-01 14:54:23
 */
@DubboService
@Service
public class StoreServiceImpl implements StoreService {
    private final StoreLocalService storeLocalService;
    private final ObjectNameService objectNameService;
    private final FileStoreService fileStoreService;

    public StoreServiceImpl(StoreLocalService storeLocalService, ObjectNameService objectNameService,
                            FileStoreService fileStoreService) {
        this.storeLocalService = storeLocalService;
        this.objectNameService = objectNameService;
        this.fileStoreService = fileStoreService;
    }

    @Override
    public void updateStoreProperties(StoreProperties storeProperties) {
        storeLocalService.updateStoreProperties(storeProperties);
    }

    @Override
    public String getUploadToken(int userId, int channelId) {
        String secretKey = storeLocalService.getSecretKey();
        String action = ChannelAction.upload.getName();
        long expireAt = System.currentTimeMillis() + 3600*1000;
        OssPayload ossPayload = new OssPayload(action, channelId, userId);
        return JwtUtil.createToken(ossPayload, expireAt, secretKey);
    }

    @Override
    public void createChannel(int userId, ObjectChannel channel) {
        String objectName = channel.getPrefix();
        objectNameService.createParentDirs(objectName, ObjectScope.PUBLIC.getCode());
        storeLocalService.addObjectChannel(channel);
    }

    @Override
    public StoreInfo getStoreInfo() {
        List<ObjectChannel> objectChannels = storeLocalService.getObjectChannels();
        List<StoreDiskDto> list = fileStoreService.getStoreDisks().stream()
                .map(StoreDiskDto::new)
                .collect(Collectors.toList());
        return new StoreInfo(storeLocalService.getStoreProperties(), objectChannels, list);
    }
}
