package com.atlassian.bitbucket.scm;

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.bitbucket.util.Weighted;
import org.dom4j.Attribute;
import org.dom4j.Element;

import javax.annotation.Nonnull;

public abstract class BaseWeightedModuleDescriptor<T>
        extends AbstractModuleDescriptor<T>
        implements Weighted, Comparable<BaseWeightedModuleDescriptor<T>> {

    private int weight;

    public BaseWeightedModuleDescriptor(ModuleFactory moduleFactory, int defaultWeight) {
        super(moduleFactory);

        weight = defaultWeight;
    }

    @Override
    public int compareTo(@Nonnull BaseWeightedModuleDescriptor<T> otherDescriptor) {
        return Weighted.COMPARABLE.compare(this, otherDescriptor);
    }

    public int getWeight() {
        return weight;
    }

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

        Attribute weightAttr = element.attribute("weight");
        if (weightAttr != null) {
            try {
                weight = Integer.parseInt(weightAttr.getValue());
            } catch (NumberFormatException e) {
                throw new PluginParseException("The 'weight' attribute must be a number.", e);
            }
        }
    }
}
