/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.job.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.crunii.micro.common.job.ScanGroup;

/**
 * @author 田平 create 2020年3月27日上午10:47:30
 *
 */
public class FetchUtil {

	/**
	 * 按占比获取获取数据
	 * @param groups 保证查询尽量多的数据
	 * @param max 最多去的数据条数
	 * @return
	 */
	public static <T extends ScanGroup> List<T> fetchByPercent(List<T> groups, int max) {
		int groupSize = groups.size();
		if (groups.size() > max) {
			Map<String, Integer> map = new HashMap<String, Integer>();
			for (ScanGroup group : groups) {
				Integer size = map.get(group.getGroupId());
				if (size == null) {
					map.put(group.getGroupId(), 1);
				} else {
					map.put(group.getGroupId(), size + 1);
				}
			}
			for (Entry<String, Integer> entry : map.entrySet()) {
				// 按比例分配最少一条,余数大于0多取一条，保证最大数量
				int v = max * entry.getValue() / groupSize;
				int remainder = (max * entry.getValue()) % groupSize;
				if (remainder > 0) {
					v = v + 1;
				}
				entry.setValue(v);
			}
			List<T> newJobs = new ArrayList<T>(max + map.entrySet().size());
			for (Entry<String, Integer> entry : map.entrySet()) {
				int input = 0;
				String key = entry.getKey();
				int fetchSize = entry.getValue();
				Iterator<T> entities = groups.iterator();
				while (entities.hasNext()) {
					T entity = entities.next();
					if (key != null && key.equals(entity.getGroupId())) {
						entities.remove();
						newJobs.add(entity);
						input++;
					} else if (key == null && entity.getGroupId() == null) {
						entities.remove();
						newJobs.add(entity);
						input++;
					}
					if (input >= fetchSize) {
						break;
					}
				}
			}
			return newJobs;
		} else {
			return groups;
		}
	}
}
