package com.atlassian.bitbucket.internal.stp;

import com.atlassian.bitbucket.hook.BaseScmHookModuleDescriptor;
import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.PluginAccessor;
import com.atlassian.plugin.predicate.ModuleDescriptorPredicate;
import com.atlassian.support.tools.spi.RootLevelSupportInfoAppender;
import com.atlassian.support.tools.spi.SupportInfoBuilder;

import static com.atlassian.bitbucket.internal.stp.StpKeys.*;

/**
 * Adds information about the commit hooks to STP.
 *
 * @since 2.5
 */
public class CommitHooksPluginInfo extends RootLevelSupportInfoAppender {

    private final PluginAccessor pluginAccessor;

    public CommitHooksPluginInfo(PluginAccessor pluginAccessor) {
        this.pluginAccessor = pluginAccessor;
    }

    @Override
    protected void addSupportInfo(SupportInfoBuilder builder) {
        addCommitHookPluginInformation(builder.addCategory(PLUGINS_COMMIT_HOOKS_MODULES));
    }

    private void addCommitHookPluginInformation(SupportInfoBuilder builder) {
        Iterable<ModuleDescriptor<Object>> modules = pluginAccessor.getModuleDescriptors(new ModuleDescriptorPredicate<Object>() {
            public boolean matches(ModuleDescriptor<?> moduleDescriptor) {
                return (moduleDescriptor instanceof BaseScmHookModuleDescriptor);
            }
        });
        for (ModuleDescriptor module : modules) {
            SupportInfoBuilder hookBuilder = builder.addCategory(PLUGINS_COMMIT_HOOKS_MODULE);
            hookBuilder.addValue(PLUGINS_COMMIT_HOOKS_KEY, module.getCompleteKey());
            hookBuilder.addValue(PLUGINS_COMMIT_HOOKS_DESCRIPTION, module.getDescription());
            if (module.getModuleClass() != null) {
                //when disabled the module class is set to null!
                hookBuilder.addValue(PLUGINS_COMMIT_HOOKS_CLASS, module.getModuleClass().getName());
            }
            hookBuilder.addValue(PLUGINS_COMMIT_HOOKS_SOURCE, module.getPlugin().getKey());
            hookBuilder.addContext(module);
        }
    }

}
