package com.atlassian.bitbucket.mesh.git.hook;

import com.atlassian.bitbucket.mesh.config.HooksConfig;
import com.atlassian.bitbucket.mesh.execution.ExecutionManager;
import com.atlassian.bitbucket.mesh.repository.RepositoryManager;

import javax.annotation.Nonnull;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;

import static java.util.Objects.requireNonNull;

public class ConfigurableGitHookService extends DefaultGitHookService {

    private final ConcurrentMap<String, GitHookHandler> customHandlers;

    public ConfigurableGitHookService(HooksConfig config, ExecutionManager executionManager,
                                      ExecutorService executor, List<GitHookHandler> handlers,
                                      RepositoryManager repositoryManager, Path tempDir) {
        super(config, executionManager, executor, handlers, repositoryManager, tempDir);

        customHandlers = new ConcurrentHashMap<>();
    }

    public void addHandler(@Nonnull GitHookHandler handler) {
        requireNonNull(handler, "handler");
        customHandlers.put(handler.getHookName(), handler);
    }

    public void removeHandler(@Nonnull String hookName) {
        customHandlers.remove(hookName);
    }

    public void reset() {
        customHandlers.clear();
    }

    @Override
    protected GitHookHandler getDefaultHandler(String hookName) {
        GitHookHandler handler = customHandlers.get(hookName);
        return handler == null ? super.getDefaultHandler(hookName) : handler;
    }
}
