package cn.reghao.oss.store.db.repository;

import cn.reghao.oss.store.api.dto.ObjectChannel;
import cn.reghao.oss.store.api.dto.media.ImageUrlDto;
import cn.reghao.oss.store.db.mapper.ImageFileMapper;
import cn.reghao.oss.store.model.po.ImageFile;
import cn.reghao.oss.store.service.StoreChannelService;
import cn.reghao.oss.store.service.StoreLocalCache;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author reghao
 * @date 2023-08-28 15:00:43
 */
@Repository
public class ImageRepository {
    private final ImageFileMapper imageFileMapper;
    private final ObjectRepository objectRepository;
    private final StoreLocalCache storeLocalCache;
    private StoreChannelService storeChannelService;

    public ImageRepository(ImageFileMapper imageFileMapper, ObjectRepository objectRepository,
                           StoreLocalCache storeLocalCache, StoreChannelService storeChannelService) {
        this.imageFileMapper = imageFileMapper;
        this.objectRepository = objectRepository;
        this.storeLocalCache = storeLocalCache;
        this.storeChannelService = storeChannelService;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveImageFiles(List<ImageFile> imageFiles) {
        imageFileMapper.saveAll(imageFiles);
    }

    public void deleteByImageFileIds(List<String> imageFileIds) {
        imageFileIds.forEach(this::deleteImageFile);
    }

    public void deleteImageFile(String imageFileId) {
        List<String> objectIds = imageFileMapper.findByImageFileId(imageFileId).stream()
                .map(ImageFile::getObjectId)
                .collect(Collectors.toList());
        deleteImageFile0(imageFileId, objectIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteImageFile0(String imageFileId, List<String> objectIds) {
        imageFileMapper.deleteByImageFileId(imageFileId);
    }

    public List<ImageFile> findImageFiles(String imageFileId) {
        return imageFileMapper.findByImageFileId(imageFileId);
    }

    public List<ImageFile> getImageFiles(List<String> imageFileIds) {
        return imageFileMapper.findByImageFileIds(new HashSet<>(imageFileIds));
    }

    public List<ImageUrlDto> getImageUrls(Set<String> imageFileIds) {
        List<ImageUrlDto> list = new ArrayList<>();
        for (String imageFileId : imageFileIds) {
            ImageUrlDto imageUrlDto = getImageUrl(imageFileId);
            if (imageUrlDto != null) {
                list.add(imageUrlDto);
            }
        }

        return list;
    }

    public ImageUrlDto getImageUrl(String imageFileId) {
        return null;
    }
}
