package com.atlassian.stash.internal.plugin.hooks.allapprovers;

import com.atlassian.bitbucket.event.repository.RepositoryDeletedEvent;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;

import javax.annotation.Nonnull;

/**
 * Holds the configuration for the merge check {@link AllApproversMergeCheck}.
 */
public class AllApproversMergeCheckConfig {

    private static final String PLUGIN_KEY = "com.atlassian.bitbucket.server.bitbucket-bundled-hooks";
    static final String MODULE_KEY = PLUGIN_KEY + ":all-approvers-merge-check-settings-resources";

    private final EventPublisher eventPublisher;
    private final PluginSettings pluginSettings;

    public AllApproversMergeCheckConfig(EventPublisher eventPublisher, PluginSettingsFactory factory) {
        this.eventPublisher = eventPublisher;
        this.pluginSettings = factory.createSettingsForKey(PLUGIN_KEY);
    }

    /**
     * Makes sure the plugin setting is deleted if the repository is removed.
     *
     * @param event repository deletion event
     */
    @EventListener
    public void onRepositoryDeleted(RepositoryDeletedEvent event) {
        pluginSettings.remove(createKey(event.getRepository()));
    }

    /**
     * Returns {@code true} if all reviewers must approve before the pull request can be merged
     *
     * @param repository repository containing the pull request
     * @return boolean {@code true} if all the reviewers must approve before the pull request can be merged
     */
    public boolean areAllApproversRequired(@Nonnull Repository repository) {
        Object allApproversRequired = pluginSettings.get(createKey(repository));

        return allApproversRequired instanceof String && Boolean.parseBoolean((String) allApproversRequired);
    }

    /**
     * Sets if all reviewers must approve before a pull request is merged
     *
     * @param repository           repository containing the pull request
     * @param allApproversRequired whether all reviewers must approve before the pull request can be merged
     */
    public void setAllApproversRequired(@Nonnull Repository repository, boolean allApproversRequired) {
        pluginSettings.put(createKey(repository), Boolean.toString(allApproversRequired));
        eventPublisher.publish(new AllApproversMergeCheckConfigChangedEvent(this, repository, allApproversRequired));
    }

    private String createKey(Repository repository) {
        return "repo." + repository.getId() + ".requireAllApprovers";
    }
}
