package cn.reghao.oss.store.rpc;

import cn.reghao.oss.store.db.mapper.*;
import cn.reghao.oss.store.model.po.AudioFile;
import cn.reghao.oss.store.model.po.ImageFile;
import cn.reghao.oss.store.model.po.VideoFile;
import cn.reghao.oss.api.constant.ObjectScope;
import cn.reghao.oss.api.iface.PermissionService;
import cn.reghao.oss.store.db.mapper.AudioFileMapper;
import cn.reghao.oss.store.db.mapper.FileMetaMapper;
import cn.reghao.oss.store.db.mapper.ImageFileMapper;
import cn.reghao.oss.store.db.mapper.VideoFileMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2023-06-02 10:07:42
 */
@DubboService
@Service
public class PermissionServiceImpl implements PermissionService {
    private final ImageFileMapper imageFileMapper;
    private final AudioFileMapper audioFileMapper;
    private final VideoFileMapper videoFileMapper;
    private final FileMetaMapper fileMetaMapper;

    public PermissionServiceImpl(ImageFileMapper imageFileMapper, AudioFileMapper audioFileMapper,
                                 VideoFileMapper videoFileMapper, FileMetaMapper fileMetaMapper) {
        this.imageFileMapper = imageFileMapper;
        this.audioFileMapper = audioFileMapper;
        this.videoFileMapper = videoFileMapper;
        this.fileMetaMapper = fileMetaMapper;
    }

    @Override
    public void setDirPermission(String prefix, int scope) {
    }

    @Override
    public void getDirPermission(String prefix) {
        for (ObjectScope scope : ObjectScope.values()) {
        }
    }

    @Override
    public void setVideoPermission(String videoFileId, int scope) {
        List<String> objectIds = videoFileMapper.findByVideoFileId(videoFileId).stream()
                .map(VideoFile::getObjectId)
                .collect(Collectors.toList());
        if (!objectIds.isEmpty()) {
            fileMetaMapper.updateScopeByObjectIds(scope, objectIds);
        }
    }

    @Override
    public void setAudioPermission(String audioFileId, int scope) {
        List<String> objectIds = audioFileMapper.findByAudioFileId(audioFileId).stream()
                .map(AudioFile::getObjectId)
                .collect(Collectors.toList());
        if (!objectIds.isEmpty()) {
            fileMetaMapper.updateScopeByObjectIds(scope, objectIds);
        }
    }

    @Override
    public void setImagesPermission(Set<String> imageFileIds, int scope) {
        List<String> objectIds = imageFileMapper.findByImageFileIds(imageFileIds).stream()
                .map(ImageFile::getObjectId)
                .collect(Collectors.toList());
        if (!objectIds.isEmpty()) {
            fileMetaMapper.updateScopeByObjectIds(scope, objectIds);
        }
    }
}
