package com.atlassian.stash.internal.cluster;

import com.atlassian.bitbucket.cluster.ClusterInformation;
import com.atlassian.bitbucket.cluster.ClusterNode;
import com.hazelcast.core.Cluster;
import com.hazelcast.core.HazelcastInstance;

import javax.annotation.Nonnull;
import java.util.Set;

import static com.atlassian.stash.internal.cluster.HazelcastClusterNode.sort;
import static com.atlassian.stash.internal.cluster.HazelcastClusterNode.transform;
import static com.google.common.base.Preconditions.checkNotNull;

public class HazelcastClusterInformation implements ClusterInformation {

    private final Cluster cluster;
    private final HazelcastInstance hazelcast;

    public HazelcastClusterInformation(HazelcastInstance hazelcast) {
        this.hazelcast = checkNotNull(hazelcast, "hazelcast");

        cluster = checkNotNull(hazelcast.getCluster(), "hazelcast.cluster");
    }

    @Nonnull
    @Override
    public ClusterNode getLocalNode() {
        return new HazelcastClusterNode(cluster.getLocalMember());
    }

    @Nonnull
    @Override
    public Set<ClusterNode> getNodes() {
        return sort(transform(cluster.getMembers()));
    }

    @Override
    public boolean isRunning() {
        return hazelcast.getLifecycleService().isRunning();
    }
}
