package com.atlassian.bitbucket.internal.mirroring.upstream;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.mirroring.upstream.MirroringDisabledException;
import com.atlassian.bitbucket.server.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DefaultSmartMirroringFeature implements SmartMirroringFeature {

    private final FeatureManager featureManager;
    private final I18nService i18nService;
    private final ApplicationPropertiesService propertiesService;

    @Autowired
    public DefaultSmartMirroringFeature(FeatureManager featureManager, I18nService i18nService,
                                        ApplicationPropertiesService propertiesService) {
        this.featureManager = featureManager;
        this.i18nService = i18nService;
        this.propertiesService = propertiesService;
    }

    @Override
    public void checkEnabled() {
        ApplicationMode mode = propertiesService.getMode();
        if (mode != ApplicationMode.DEFAULT) {
            throw new IncompatibleApplicationModeException(
                    i18nService.createKeyedMessage("bitbucket.mirroring.incompatibleApplicationMode", mode));
        }

        if (!isAvailable()) {
            throw new MirroringDisabledException(i18nService.createKeyedMessage("bitbucket.mirroring.feature.unavailable"));
        }

        if (!isEnabled()) {
            throw new MirroringDisabledException(i18nService.createKeyedMessage("bitbucket.mirroring.feature.disabled"));
        }

    }

    @Override
    public boolean isAvailable() {
        return featureManager.isAvailable(StandardFeature.SMART_MIRRORS);
    }

    @Override
    public boolean isEnabled() {
        return featureManager.isEnabled(StandardFeature.SMART_MIRRORS);
    }
}
