package cn.reghao.tnb.content.app.data.db.repository;

import cn.reghao.jutil.jdk.db.Page;
import cn.reghao.tnb.content.app.data.db.mapper.ImagePostMapper;
import cn.reghao.tnb.content.app.data.db.mapper.ImageFileMapper;
import cn.reghao.tnb.content.app.data.model.po.ImagePost;
import cn.reghao.tnb.content.app.data.model.po.ImageFile;
import cn.reghao.tnb.content.app.data.model.vo.ImageAlbumQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * @author reghao
 * @date 2023-08-28 15:00:43
 */
@Repository
public class ImageRepository {
    private final ImagePostMapper imagePostMapper;
    private final ImageFileMapper imageFileMapper;

    public ImageRepository(ImagePostMapper imagePostMapper, ImageFileMapper imageFileMapper) {
        this.imagePostMapper = imagePostMapper;
        this.imageFileMapper = imageFileMapper;
    }

    public void saveImageAlbum(ImagePost imagePost) {
        imagePostMapper.save(imagePost);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addAlbumImage(long albumId, int imageCount, ImageFile imageFile) {
        imagePostMapper.updateAlbumCount(albumId, imageCount);
        imageFileMapper.save(imageFile);
    }

    public int countByCriteria(ImageAlbumQuery imageAlbumQuery) {
        int total = imagePostMapper.countByCriteria(imageAlbumQuery);
        return total;
    }

    public List<ImagePost> findImageAlbumByPage(Page page, ImageAlbumQuery imageAlbumQuery) {
        List<ImagePost> list = imagePostMapper.findImageAlbumByPage(page, imageAlbumQuery);
        return list;
    }

    public int countImageFiles(long albumId) {
        return imageFileMapper.countByAlbumId(albumId).size();
    }

    public List<String> getImageFileIds(long albumId, Page page) {
        return imageFileMapper.findImageFileIdsByPage(page, albumId);
    }

    public List<ImageFile> getImageFiles(List<String> imageFileIds) {
        if (imageFileIds.isEmpty()) {
            return Collections.emptyList();
        }

        return imageFileMapper.findByImageFileIds(imageFileIds);
    }

    public ImageFile getByUrl(String url) {
        return imageFileMapper.findByUrl(url);
    }

    public ImagePost getImageAlbum(long albumId) {
        ImageAlbumQuery imageAlbumQuery = new ImageAlbumQuery.Builder()
                .albumId(albumId)
                .build();

        Page page = new Page(1, 1);
        List<ImagePost> list = imagePostMapper.findImageAlbumByPage(page, imageAlbumQuery);
        return list.isEmpty() ? null : list.get(0);
    }
}
