package com.atlassian.stash.internal.cluster;

import com.atlassian.stash.internal.license.LicenseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.io.IOException;

import static com.atlassian.stash.internal.cluster.ClusterJoinCheckAction.PASSIVATE_OTHER_NODE;

/**
 * {@link ClusterJoinCheck join check} that only accepts new nodes joining if the instance is correctly licensed for
 * clustering.
 */
@Component
public class LicenseClusterJoinCheck implements ClusterJoinCheck {

    private static final String UNLICENSED_MESSAGE = "The instance is not licensed for clustering";

    private final LicenseHelper licenseHelper;

    @Autowired
    public LicenseClusterJoinCheck(LicenseHelper licenseHelper) {
        this.licenseHelper = licenseHelper;
    }

    @Nonnull
    @Override
    public ClusterJoinCheckResult accept(@Nonnull ClusterJoinRequest request) throws IOException {
        return isClusteringEnabledResult();
    }

    @Nonnull
    @Override
    public ClusterJoinCheckResult connect(@Nonnull ClusterJoinRequest request) throws IOException {
        return isClusteringEnabledResult();
    }

    @Nonnull
    @Override
    public String getName() {
        return getClass().getName();
    }

    @Override
    public int getOrder() {
        return 5;
    }

    @Nonnull
    @Override
    public ClusterJoinCheckResult onUnknown(@Nonnull ClusterJoinRequest request) {
        return isClusteringEnabledResult();
    }

    private ClusterJoinCheckResult isClusteringEnabledResult() {
        return licenseHelper.isClusteringEnabled(false) ? ClusterJoinCheckResult.OK :
                ClusterJoinCheckResult.passivate(PASSIVATE_OTHER_NODE, UNLICENSED_MESSAGE);
    }

}
