package com.atlassian.stash.internal.cluster;

import com.atlassian.bitbucket.cluster.ClusterInformation;
import com.atlassian.bitbucket.cluster.ClusterService;
import com.atlassian.bitbucket.license.LicenseService;
import com.atlassian.extras.api.bitbucket.BitbucketServerLicense;
import com.atlassian.plugin.spring.AvailableToPlugins;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Nonnull;

@AvailableToPlugins(ClusterService.class)
@Service("clusterService")
public class HazelcastClusterService implements ClusterService {

    private final ClusterInformation clusterInformation;
    private final HazelcastInstance hazelcast;
    private final LicenseService licenseService;

    @Autowired
    public HazelcastClusterService(HazelcastInstance hazelcast, LicenseService licenseService) {
        this.hazelcast = hazelcast;
        this.licenseService = licenseService;

        clusterInformation = new HazelcastClusterInformation(hazelcast);
    }

    @Nonnull
    @Override
    public ClusterInformation getInformation() {
        return clusterInformation;
    }

    @Nonnull
    @Override
    public String getNodeId() {
        return clusterInformation.getLocalNode().getId();
    }

    @Override
    public boolean isAvailable() {
        BitbucketServerLicense license = licenseService.get();
        return (license != null && license.isClusteringEnabled()) && hazelcast.getLifecycleService().isRunning();
    }

    @Override
    public boolean isClustered() {
        return isAvailable() && hazelcast.getCluster().getMembers().size() > 1;
    }
}
