package com.wecloud.im.ws.cache;

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(String appKey, String clientId, String longChannelId) {
        for(UserStateListener listener: listeners) {
            listener.onLineEvent(appKey, clientId, longChannelId);
        }
    }

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

    public abstract void onLineEvent(String appKey, String clientId, String longChannelId);

    public abstract void offlineEvent(String appKey, String clientId, String longChannelId);
}
