package com.atlassian.stash.internal.plugin;

import com.atlassian.plugin.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.notification.NotificationHandler;
import org.dom4j.Element;

import javax.annotation.Nonnull;

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

/**
 * <p>Module descriptor for providing {@link NotificationHandler} implementations.</p>
 *
 * <p>Usage example:</p>
 * <pre>
 *     &lt;notification-handler
 *              key="generalCommentedAddedHandler"
 *              class="com.atlassian.stash.notification.pull.handlers.GeneralCommentAddedNotificationHandler"
 *              notification="com.atlassian.stash.notification.pull.GeneralCommentAddedNotification" /&gt;
 * </pre>
 *
 * @since 1.3
 */
public class NotificationHandlerModuleDescriptor extends AbstractModuleDescriptor<NotificationHandler> {

    public static final String XML_ELEMENT_NAME = "notification-handler";

    private String notificationClass;

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

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

    @Override
    public void init(@Nonnull final Plugin plugin, @Nonnull final Element element) throws PluginParseException {
        super.init(plugin, element);
        this.notificationClass = element.attributeValue("notification", "");
    }

    @Override
    public NotificationHandler getModule() {
        return moduleFactory.createModule(moduleClassName, this);
    }

    public String getNotificationClass() {
        return notificationClass;
    }

}
