package com.atlassian.bitbucket.hook;

import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.module.ModuleFactory;
import com.atlassian.bitbucket.scm.BaseWeightedModuleDescriptor;
import com.atlassian.bitbucket.util.Weighted;
import com.google.common.collect.Ordering;

import javax.annotation.Nonnull;
import java.util.function.Function;

/**
 * Base implementation for scm hook module descriptor.
 *
 * @param <T> the module type
 */
public abstract class BaseScmHookModuleDescriptor<T> extends BaseWeightedModuleDescriptor<T> {

    private static final int DEFAULT_WEIGHT = 1000;

    private static final Function<ModuleDescriptor, String> TO_MODULE_KEY = input -> null == input ? "" : input.getCompleteKey();

    private static final Ordering MODULE_KEY_ORDERING = Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast().
            onResultOf(TO_MODULE_KEY::apply);

    private T module;

    public BaseScmHookModuleDescriptor(@Nonnull ModuleFactory moduleFactory) {
        super(moduleFactory, DEFAULT_WEIGHT);
    }

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

    @Override
    public T getModule() {
        return module;
    }

    @Override
    public void enabled() {
        super.enabled();
        module = moduleFactory.createModule(moduleClassName, this);
    }

}
