package com.huigou.uasp.bmp.opm.application.impl;

import com.huigou.uasp.bmp.common.easysearch.domain.model.EasySearchParse;
import com.huigou.uasp.bmp.opm.application.MemEasySearcher;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * @author yonghuan
 */
@Component
public class MemEasySearcherImpl<T> implements MemEasySearcher<T> {

    @Override
    public Map<String, Object> search(Iterable<T> source, EasySearchParse searchParse, Pageable pageable, Predicate<? super T> filter) {
        long count = searchInternal(source, filter).count();
        List<T> datas = count > 0
                ? searchInternal(source, filter)
                    .skip(pageable.getOffset())
                    .limit(pageable.getPageSize())
                    .collect(Collectors.toList())
                : Collections.emptyList();
        PageImpl<T> page = new PageImpl(datas, pageable, count);

        Map<String, Object> model = new HashMap<>(5);
        model.put("intPage", page.getNumber() + 1);
        model.put("sumPage", page.getTotalPages());
        model.put("count", count);
        model.put("width", searchParse.getWidth());
        model.put("headLength", searchParse.getHeadLength());
        model.put("headList", searchParse.getFields());
        model.put("datas", datas);
        return model;
    }

    private Stream<T> searchInternal(Iterable<T> source, Predicate<? super T> filter) {
        return Optional.ofNullable(filter)
                .map(paramValue -> StreamSupport.stream(source.spliterator(), false).filter(filter))
                .orElseGet(() -> StreamSupport.stream(source.spliterator(), false));
    }

}
