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 org.dom4j.Element;

import java.util.Locale;

import static com.atlassian.plugin.util.validation.ValidationPattern.test;
import static com.google.common.base.MoreObjects.firstNonNull;

/**
 * @since 2.12
 */
public class LanguageModuleDescriptor extends AbstractModuleDescriptor<Locale> {

    public static final String XML_ELEMENT_NAME = "language".intern();

    private volatile Locale locale;

    public LanguageModuleDescriptor(ModuleFactory moduleFactory) {
        super(moduleFactory);

    }

    @Override
    public Locale getModule() {
        // Ideally we use Language, except that we're in platform and don't have access to service-api
        return locale;
    }

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

        // Matches the module attributes required by Confluence/JIRA
        String language = element.attributeValue("language");
        String country = element.attributeValue("country");
        String variant = element.attributeValue("variant");
        locale = new Locale(language, firstNonNull(country, ""), firstNonNull(variant, ""));
    }

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