package cn.axzo.msg.center.message.service.card.domain;

import cn.axzo.im.center.api.vo.PersonAccountAttribute;
import cn.axzo.im.center.api.vo.req.ExcludePushPayload;
import cn.axzo.im.center.common.enums.AppTypeEnum;
import cn.axzo.msg.center.domain.entity.Card;
import cn.axzo.msg.center.nimpush.PushChannel;
import cn.axzo.msg.center.nimpush.device.PushDevice;
import cn.axzo.msg.center.nimpush.device.PushDeviceSnapshots;
import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author yanglin
 */
@Getter
@RequiredArgsConstructor
public class CardGroup {

    private final CardGroupKey groupKey;
    private final List<Card> cards = Collections.synchronizedList(new ArrayList<>());

    public void addCard(Card card) {
        cards.add(card);
    }

    public List<PersonAccountAttribute> buildReceiverAccounts() {
        return getCards().stream().map(card -> {
            PersonAccountAttribute account = new PersonAccountAttribute();
            account.setPersonId(card.getReceiverPersonId() + "");
            account.setOuId(card.getReceiverOuId());
            account.setWorkspaceId(card.getReceiverWorkspaceId());
            account.setAppType(groupKey.getAppType());
            return account;
        }).collect(toList());
    }

    public List<ExcludePushPayload> buildNimPushExcludes(PushDeviceSnapshots deviceSnapshots) {
        AppTypeEnum appType = groupKey.getAppType();
        return getCards().stream().map(Card::getReceiverPersonId)
                .filter(personId -> {
                    PushDevice device = deviceSnapshots.getDevice(personId);
                    return !device.shouldPush(appType, PushChannel.NIM);
                })
                .map(personId -> {
                    ExcludePushPayload exclude = new ExcludePushPayload();
                    exclude.setPersonId(personId + "");
                    exclude.setAppType(appType);
                    return exclude;
                })
                .collect(toList());
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

}