package com.bcxin.backend.domain.syncs.listeners;

import com.bcxin.backend.domain.SimpleLocalLockComponent;
import com.bcxin.backend.domain.syncs.events.SyncDataQueueApplicationEvent;
import com.bcxin.backend.domain.syncs.services.DataSyncQueueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class SyncDataQueueEventListener implements ApplicationListener<SyncDataQueueApplicationEvent> {
    private final static Logger logger = LoggerFactory.getLogger(SyncDataQueueEventListener.class);
    private final Collection<DataSyncQueueService> dataSyncQueueServices;
    private final SimpleLocalLockComponent simpleLocalLockComponent;

    public SyncDataQueueEventListener(ApplicationContext applicationContext,
                                      SimpleLocalLockComponent simpleLocalLockComponent) {
        this.dataSyncQueueServices = applicationContext.getBeansOfType(DataSyncQueueService.class).values();
        this.simpleLocalLockComponent = simpleLocalLockComponent;
    }

    @Async
    @Override
    public void onApplicationEvent(SyncDataQueueApplicationEvent event) {
        String lockSyncKeyId = event.getDataQueueEntity().getFormSyncId();
        try {
            if (this.simpleLocalLockComponent.enter(lockSyncKeyId)) {
                logger.info("SyncDataQueueEventListener中触发DataSyncQueue的执行({}), 表({})", lockSyncKeyId, event.getDataQueueEntity().getName());
                this.dataSyncQueueServices.forEach(dataSyncQueueService -> {
                    dataSyncQueueService.dispatch(event.getDataQueueEntity());
                });
            }
        } finally {
            this.simpleLocalLockComponent.exit(lockSyncKeyId);
        }
    }
}
