package cn.axzo.msg.center.message.service.impl.oldmsg;

import cn.axzo.msg.center.service.dto.IdentityDTO;
import cn.axzo.msg.center.service.general.response.GeneralMessageOldDataStatisticResponse;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author yanglin
 */
@Data
public class OldMsgStatCacheValue {

    private List<IdentityResponse> identityResponses;

    public Optional<GeneralMessageOldDataStatisticResponse> findResponse(Collection<IdentityDTO> identities) {
        if (CollectionUtils.isEmpty(identityResponses))
            return Optional.empty();
        return identityResponses.stream()
                .filter(response -> response.isIdentitiesMatch(identities))
                .map(IdentityResponse::getResponse)
                .findFirst();
    }

    public void addIdentityResponse(IdentityResponse identityResponse) {
        if (identityResponses == null)
            identityResponses = new ArrayList<>();
        identityResponses.add(identityResponse);
    }

    void clear() {
        if (identityResponses == null) return;
        for (IdentityResponse identityResponse : identityResponses) {
            if (identityResponse.response != null)
                identityResponse.response.setReloadForeground(null);
        }
    }

    @Data
    public static class IdentityResponse {
        private GeneralMessageOldDataStatisticResponse response;
        private Set<IdentityDTO> identities;

        public boolean isIdentitiesMatch(Collection<IdentityDTO> identities) {
            // 比较时忽略顺序
            return this.identities.equals(new HashSet<>(identities));
        }
    }
}
