
package cn.axzo.msg.center.nimpush.device;

import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.groupingBy;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.axzo.epic.client.vo.response.ApkDeviceMaxCodeResp;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;

/**
 * @author yanglin
 */
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
public class PushDeviceSnapshots {

	private final Map<Long, PushDevice> cache = new ConcurrentHashMap<>();
	private final PushDeviceService pushDeviceService;
	private final List<ApkDeviceMaxCodeResp> devices;

	private Map<Long, List<ApkDeviceMaxCodeResp>> personId2Devices;

	public PushDevice getDevice(Long personId) {
		return cache.computeIfAbsent(personId, this::createDevice);
	}

	private PushDevice createDevice(Long personId) {
		if (personId2Devices == null)
			personId2Devices = devices.stream().collect(groupingBy(ApkDeviceMaxCodeResp::getPersonId));
		List<ApkDeviceMaxCodeResp> personDevices = personId2Devices.getOrDefault(personId, emptyList());
		return new PushDevice(pushDeviceService, personDevices);
	}

}