package com.atlassian.bitbucket.auth;

import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.StateAware;
import com.atlassian.plugin.module.ModuleFactory;
import com.atlassian.bitbucket.scm.BaseWeightedModuleDescriptor;
import org.dom4j.Attribute;
import org.dom4j.Element;

import javax.annotation.Nonnull;

public class HttpAuthenticationHandlerModuleDescriptor extends BaseWeightedModuleDescriptor<HttpAuthenticationHandler> {

    public static final String XML_ELEMENT_NAME = "http-auth-handler";

    private boolean captchaSupport = true;
    private volatile HttpAuthenticationHandler module;

    protected HttpAuthenticationHandlerModuleDescriptor(ModuleFactory moduleFactory) {
        super(moduleFactory, 50);
    }

    @Override
    public void disabled() {
        if (module instanceof StateAware) {
            ((StateAware) module).disabled();
        }
        module = null;

        super.disabled();
    }

    @Override
    public HttpAuthenticationHandler getModule() {
        if (module == null) {
            module = moduleFactory.createModule(moduleClassName, this);

        }
        return module;
    }

    @Override
    public void init(@Nonnull Plugin plugin, @Nonnull Element element) throws PluginParseException {
        super.init(plugin, element);

        Attribute attribute = element.attribute("captcha-support");
        if (attribute != null) {
            captchaSupport = Boolean.parseBoolean(attribute.getValue());
        }
    }

    public boolean isCaptchaSupported() {
        return captchaSupport;
    }

}