package com.lanyuanxiaoyao.service.scheduler.quartz.distribute.cluster;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.scheduler.quartz.distribute.strategy.AvailableStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 集群
 *
 * @author ZhangJiacheng
 * @date 2023-06-08
 */
public class Cluster {
    private static final Logger logger = LoggerFactory.getLogger(Cluster.class);

    private final String cluster;
    private final String queue;
    private final AvailableStrategy availableStrategy;

    public Cluster(String cluster, String queue) {
        this(cluster, queue, null);
    }

    public Cluster(String cluster, String queue, AvailableStrategy availableStrategy) {
        this.cluster = cluster;
        this.queue = queue;
        this.availableStrategy = availableStrategy;
    }

    public String cluster() {
        return cluster;
    }

    public String queue() {
        return queue;
    }

    public boolean available() {
        try {
            if (ObjectUtil.isNull(availableStrategy)) {
                return true;
            }
            return availableStrategy.available();
        } catch (Throwable throwable) {
            logger.error(StrUtil.format("Check cluster {} available fail", this.cluster), throwable);
        }
        return false;
    }

    @Override
    public String toString() {
        return "Cluster{" +
               "cluster='" + cluster + '\'' +
               ", queue='" + queue + '\'' +
               ", availableStrategy=" + availableStrategy +
               '}';
    }
}
