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

import cn.axzo.epic.client.vo.response.ApkDeviceMaxCodeResp;
import cn.axzo.im.center.common.enums.AppTypeEnum;
import cn.axzo.msg.center.nimpush.PushChannel;
import cn.axzo.msg.center.service.enums.PushTerminalEnum;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;

import java.util.List;

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

    private final PushDeviceService pushDeviceService;
    private final Long personId;

    private volatile List<ApkDeviceMaxCodeResp> cache;

    public boolean shouldPush(AppTypeEnum appType,
                              PushChannel pushChannel) {
        PushTerminalEnum pushTerminal = appType == AppTypeEnum.CMP
                ? PushTerminalEnum.B_ENTERPRISE_APP
                : PushTerminalEnum.C_WORKER_APP;
        return shouldPush(pushTerminal, pushChannel);
    }

    public boolean shouldPush(PushTerminalEnum pushTerminal,
                              PushChannel pushChannel) {
        List<ApkDeviceMaxCodeResp> devices = getDevices();
        return pushDeviceService.shouldPush(pushTerminal, pushChannel, devices);
    }

    private List<ApkDeviceMaxCodeResp> getDevices() {
        List<ApkDeviceMaxCodeResp> cache = this.cache;
        if (cache != null)
            return cache;
        synchronized (this) {
            cache = this.cache;
            if (cache == null)
                cache = this.cache = pushDeviceService.getPersonDevices(personId);
        }
        return cache;
    }

}