package com.mortals.xhx.common.utils;

import com.mortals.xhx.module.sitestat.model.SitestatEntity;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author: zxfei
 * @date: 2022/6/28 14:38
 * @description: 内存分页
 **/
public class MemoryPagination {
    /**
     * 内存分页
     *
     * @param records  待分页的数据
     * @param pageNum  当前页码
     * @param pageSize 每页显示的条数
     * @return 分页之后的数据
     */
    public static <T> List<T> pagination(List<T> records, int pageNum, int pageSize) {
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
        if (pageSize == -1) {
            pageSize = 9999;
        }

        int totalCount = records.size();
        int remainder = totalCount % pageSize;
        int pageCount = (remainder > 0) ? totalCount / pageSize + 1 : totalCount / pageSize;
        if (remainder == 0) {
            return records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        } else {
            if (pageNum == pageCount) {
                return records.stream().skip((pageNum - 1) * pageSize).limit(totalCount).collect(Collectors.toList());
            } else {
                return records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            }
        }
    }


    public static List<SitestatEntity> search(String name, List<SitestatEntity> list) {
        List<SitestatEntity> results = new ArrayList();
        Pattern pattern = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
        for (int i = 0; i < list.size(); i++) {
            Matcher matcher = pattern.matcher((list.get(i)).getSiteName());
            if (matcher.find()) {
                results.add(list.get(i));
            }
        }
        return results;
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }
}
