package com.atlassian.stash.internal.plugin;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.descriptors.AbstractModuleDescriptor;
import com.atlassian.plugin.module.ModuleFactory;
import com.atlassian.plugin.util.validation.ValidationPattern;
import com.atlassian.bitbucket.repository.RefMetadataProvider;

import static com.atlassian.plugin.util.validation.ValidationPattern.test;

/**
 * A module descriptor for a {@link RefMetadataProvider}
 *
 * @since 2.8
 */
public class RefMetadataProviderModuleDescriptor extends AbstractModuleDescriptor<RefMetadataProvider> {

    public static final String XML_ELEMENT_NAME = "ref-metadata-provider";

    private RefMetadataProvider provider;

    public RefMetadataProviderModuleDescriptor(ModuleFactory moduleFactory) {
        super(moduleFactory);
    }

    @Override
    public void disabled() {
        provider = null;
        super.disabled();
    }

    @Override
    public void enabled() {
        super.enabled();
        if (RefMetadataProvider.class.isAssignableFrom(moduleClass)) {
            provider = moduleFactory.createModule(moduleClassName, this);
        } else {
            throw new PluginParseException("ref-metadata must implement " + RefMetadataProvider.class.getSimpleName());
        }
    }

    @Override
    public RefMetadataProvider getModule() {
        return provider;
    }

    @Override
    protected void provideValidationRules(ValidationPattern pattern) {
        super.provideValidationRules(pattern);
        pattern.rule(
                test("@class").withError("class is a required attribute")
        );
    }

}
