package cn.axzo.workflow.core.engine.job;

import org.flowable.job.service.JobHandler;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * 记录每个 JOB 是否被多台机器同时处理
 *
 * @author wangli
 * @since 2024/6/28 10:28
 */
public abstract class AbstractJobHandler implements JobHandler {

    private static final Logger log = LoggerFactory.getLogger(AbstractJobHandler.class);

    protected final void log(JobEntity job) {
        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();

                // 如果是活动的，并且不是回环接口（即非本地接口）
                if (iface.isUp() && !iface.isLoopback()) {
                    List<InetAddress> addresses = Collections.list(iface.getInetAddresses());

                    // 遍历每个接口上的 IP 地址
                    for (InetAddress address : addresses) {
                        // 检查地址是否是 IPv4 类型的，并且不是回环地址
                        if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
                            log.warn(" current job ID: {} will be execution by IP:{}", job.getId(), address.getHostAddress());
                        }
                    }
                }
            }
        } catch (SocketException e) {
            // ignore
        }
    }
}
