package com.atlassian.stash.internal.web.conditions;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import com.atlassian.bitbucket.cluster.ClusterService;
import com.atlassian.stash.internal.db.DatabaseSupplier;
import com.atlassian.stash.internal.db.DatabaseSupportLevel;
import com.atlassian.stash.internal.db.DetailedDatabase;
import com.atlassian.bitbucket.util.DevModeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Checks whether the current {@link DetailedDatabase database} is unsupported.
 *
 * @since 2.2
 */
public class IsUnsupportedDatabaseCondition implements Condition {

    private static final Logger log = LoggerFactory.getLogger(IsUnsupportedDatabaseCondition.class);

    private final ClusterService clusterService;
    private final DatabaseSupplier databaseSupplier;

    public IsUnsupportedDatabaseCondition(ClusterService clusterService, DatabaseSupplier databaseSupplier) {
        this.clusterService = clusterService;
        this.databaseSupplier = databaseSupplier;
    }

    @Override
    public void init(Map<String, String> stringStringMap) throws PluginParseException {
    }

    @Override
    public boolean shouldDisplay(Map<String, Object> stringObjectMap) {
        try {
            DetailedDatabase database = databaseSupplier.get();
            if (database.isInternal() && DevModeUtils.isEnabled()) {
                //Don't show the Data Center database banner when a developer is using the internal database.
                //The banner would otherwise always be displayed because the atlassian.dev.mode-bootstrapped
                //license is always a Data Center license
                return false;
            }

            return database.getSupportLevel() != DatabaseSupportLevel.SUPPORTED ||
                    (clusterService.isAvailable() && !database.isClusterable());
        } catch (Exception e) {
            log.warn("Could not verify database support level", e);

            return false;
        }
    }
}
