package com.zcloud.personnel.positioning.command;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Component
public class AfterCommitExecutor {
    private static final Logger LOGGER = LoggerFactory.getLogger(AfterCommitExecutor.class);

    private final TaskExecutor taskExecutor;

    public AfterCommitExecutor(@Qualifier("findsSyncTaskExecutor") TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public void execute(Runnable task) {
        if (TransactionSynchronizationManager.isActualTransactionActive()
                && TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    submit(task);
                }
            });
            return;
        }
        submit(task);
    }

    private void submit(Runnable task) {
        taskExecutor.execute(() -> {
            try {
                task.run();
            } catch (Exception e) {
                LOGGER.warn("Execute FindS synchronization after local commit failed", e);
            }
        });
    }
}
