package com.bcxin.wps.repository.impls;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.bcxin.model.domain.Xfile;
import com.bcxin.service.impl.XfileService;
import com.bcxin.wps.entity.File;
import com.bcxin.wps.repository.FileRepository;
import com.bcxin.wps.entity.FileId;
import com.bcxin.wps.service.mappers.FileMapperService;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Repository
public class FileRepositoryImpl implements FileRepository {
    private final FileMapperService fileMapperService;

    public FileRepositoryImpl(FileMapperService fileMapperService) {
        this.fileMapperService = fileMapperService;
    }

    @Override
    public List<File> findByIdId(String id) {
        FileId fileId = FileId.builder().id(id).build();
        Collection<FileId> selectedFieldIds = new ArrayList<>();
        selectedFieldIds.add(fileId);

        return findAllById(selectedFieldIds);
    }

    @Override
    public List<File> findAllById(Collection<FileId> fileIds) {
        if (CollectionUtils.isEmpty(fileIds)) {
            return Collections.EMPTY_LIST;
        }

        Collection<String> selectedIds =
                fileIds.stream().map(ii -> ii.getId())
                        .collect(Collectors.toList());

        List<File> files =
                this.fileMapperService.list(new QueryWrapper<File>().in("id", selectedIds));
        if (CollectionUtils.isEmpty(files)) {
            return Collections.EMPTY_LIST;
        }

        files = files.stream()
                .sorted(Comparator.comparing(File::getVersion).reversed())
                .collect(Collectors.toList());

        return files;
    }

    @Override
    public Optional<File> findById(FileId fileId) {
        if (fileId == null) {
            return Optional.empty();
        }

        File file =
                this.fileMapperService.getOne(new QueryWrapper<File>().eq("id", fileId.getFinalId()));
        if (file == null) {
            return Optional.empty();
        }

        return Optional.of(file);
    }

    @Override
    public <S extends File> S save(S entity) {
        this.fileMapperService.save(entity);

        return entity;
    }
}
