package com.wecloud.im.ws.cache;

import com.wecloud.im.entity.ImClient;
import com.wecloud.im.ws.utils.SpringBeanUtils;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 事件源接口（被观察者）
 */
public abstract class UserStateListener {

    private static final Set<UserStateListener> listeners = new HashSet<>();

    @EventListener(ApplicationStartedEvent.class)
    private void registerEventListener() {
        Collection<UserStateListener> userStateListeners = SpringBeanUtils.getBeansOfType(UserStateListener.class);
        for(UserStateListener listener : userStateListeners) {
            listeners.add(listener);
        }
    }

    public static void addListener(UserStateListener listener) {
        listeners.add(listener);
    }

    public static void triggerOnlineEvent(Long clientId, Integer platform, String longChannelId) {
        for(UserStateListener listener: listeners) {
            listener.onLineEvent(clientId, platform, longChannelId);
        }
    }

    public static void triggerOfflineEvent(Long clientId, Integer platform, String longChannelId) {
        for(UserStateListener listener: listeners) {
            listener.offlineEvent(clientId, platform, longChannelId);
        }
    }

    public abstract void onLineEvent(Long clientId, Integer platform, String longChannelId);

    public abstract void offlineEvent(Long clientId, Integer platform, String longChannelId);
}
