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

import com.bcxin.backend.domain.syncs.events.SyncDataApplicationEvent;
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.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Collection;

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

    public SyncDataEventListener(ApplicationContext applicationContext) {
        this.dataSyncQueueServices =
                applicationContext.getBeansOfType(DataSyncQueueService.class)
                .values();
    }

    @Async
    @Override
    public void onApplicationEvent(SyncDataApplicationEvent event) {
        this.dataSyncQueueServices.parallelStream().forEach(dataSyncQueueService -> {
            try {
                dataSyncQueueService.dispatchData();
            } catch (Exception ex) {
                logger.error(String.format("同步数据(%s)执行异常", dataSyncQueueService.getClass().getName()), ex);
            }

            try {
                dataSyncQueueService.dispatchFile();
            } catch (Exception ex) {
                logger.error(String.format("同步文件(%s)执行异常", dataSyncQueueService.getClass().getName()), ex);
            }
        });
    }
}
