package cn.reghao.oss.store.rpc;

import cn.reghao.oss.store.api.constant.ObjectScope;
import cn.reghao.oss.store.api.dto.*;
import cn.reghao.oss.store.service.ObjectNameService;
import cn.reghao.oss.store.service.StoreChannelService;
import cn.reghao.oss.store.service.StoreLocalCache;
import cn.reghao.oss.store.util.JwtUtil;
import cn.reghao.oss.store.api.constant.ChannelAction;
import cn.reghao.oss.store.api.iface.StoreService;
import cn.reghao.oss.store.util.UserContext;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2023-08-01 14:54:23
 */
@DubboService
@Service
public class StoreServiceImpl implements StoreService {
    private final StoreLocalCache storeLocalCache;
    private StoreChannelService storeChannelService;
    private final ObjectNameService objectNameService;

    public StoreServiceImpl(StoreLocalCache storeLocalCache, StoreChannelService storeChannelService,
                            ObjectNameService objectNameService) {
        this.storeLocalCache = storeLocalCache;
        this.storeChannelService = storeChannelService;
        this.objectNameService = objectNameService;
    }

    @Override
    public String getUploadToken(int userId, int channelId) {
        String secretKey = storeLocalCache.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) {
        UserContext userContext = new UserContext(userId);
        String objectName = channel.getPrefix();
        objectNameService.createParentDirs(objectName, ObjectScope.PUBLIC.getCode());
        storeChannelService.addObjectChannel(channel);
    }

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

    @Override
    public StoreInfo getStoreInfo() {
        StoreProperties storeProperties = storeLocalCache.getStoreProperties();
        List<ObjectChannel> objectChannels = storeChannelService.getObjectChannels();
        List<StoreDiskDto> list = storeLocalCache.getStoreDisks();
        return new StoreInfo(storeProperties, objectChannels, list);
    }
}
