package com.mooctest.event;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;

@Component
public class EventUtil {

    private static Logger logger = LoggerFactory.getLogger(EventUtil.class);
    private EventBus eventBus;

    public EventUtil() {
        eventBus = new AsyncEventBus(Executors.newCachedThreadPool());
        eventBus.register(this);
    }

    public void register(Object listener) {
        eventBus.register(listener);
    }

    public void unregister(Object listener) {
        eventBus.unregister(listener);
    }

    public void post(Event event) {
        logger.info("event fired: {}", event.getDescription());
        eventBus.post(event);
    }

    @Subscribe
    public void logDeadEvent(Event deadEvent) {
        logger.info("dead event captured: {}", deadEvent.getDescription());
    }

}

