package com.atlassian.bitbucket.scm.cache.internal;

import com.atlassian.bitbucket.scm.cache.ScmCacheService;
import com.atlassian.bitbucket.user.SecurityService;
import com.atlassian.event.api.EventPublisher;
import org.springframework.beans.factory.config.AbstractFactoryBean;

/**
 * Factory bean that creates a {@link CacheInvalidationListener} instance.
 *
 * @since 2.0.0
 */
public class CacheInvalidationListenerFactoryBean extends AbstractFactoryBean {

    private final EventPublisher eventPublisher;
    private final Object listener;

    public CacheInvalidationListenerFactoryBean(ScmCacheService cacheService, EventPublisher eventPublisher,
                                                SecurityService securityService) {
        this.eventPublisher = eventPublisher;

        listener = createListener(cacheService, securityService);
        eventPublisher.register(listener);
    }

    @Override
    public Class getObjectType() {
        return Object.class;
    }

    @Override
    protected Object createInstance() throws Exception {
        return listener;
    }

    public void destroy() throws Exception {
        eventPublisher.unregister(listener);
    }

    private Object createListener(ScmCacheService cacheService, SecurityService securityService) {
        return new CacheInvalidationListener(cacheService, securityService);
    }
}
