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

import com.atlassian.bitbucket.mesh.repository.Repository;
import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;
import java.util.Map;
import java.util.Optional;

import static com.atlassian.bitbucket.mesh.git.GitConstants.*;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.empty;
import static java.util.Optional.of;

/**
 * Encapsulates the environment variables set when {@code pre-receive} hooks are run during a quarantined push.
 */
public class GitQuarantineEnvironment {

    private final String alternateDirs;
    private final String objectDir;
    private final String quarantinePath;
    private final Repository repository;

    public GitQuarantineEnvironment(@Nonnull Repository repository, @Nonnull String alternateDirs,
                                    @Nonnull String objectDir, @Nonnull String quarantinePath) {
        this.alternateDirs = requireNonNull(alternateDirs, "alternateDirs");
        this.objectDir = requireNonNull(objectDir, "objectDir");
        this.quarantinePath = requireNonNull(quarantinePath, "quarantinePath");
        this.repository = requireNonNull(repository, "repository");
    }

    private GitQuarantineEnvironment(Repository repository, Map<String, String> environment) {
        this(repository, environment.get(ENV_ALTERNATE_OBJECT_DIRS),
                environment.get(ENV_OBJECT_DIR), environment.get(ENV_QUARANTINE_PATH));
    }

    @Nonnull
    public static Optional<GitQuarantineEnvironment> fromEnvironment(@Nonnull Repository repository,
                                                                     @Nonnull Map<String, String> environment) {
        if (environment.containsKey(ENV_QUARANTINE_PATH)) {
            return of(new GitQuarantineEnvironment(repository, environment));
        }

        return empty();
    }

    @Nonnull
    public Map<String, String> asMap() {
        return ImmutableMap.of(
                ENV_ALTERNATE_OBJECT_DIRS, alternateDirs,
                ENV_OBJECT_DIR, objectDir,
                ENV_QUARANTINE_PATH, quarantinePath);
    }

    @Nonnull
    public String getAlternateDirs() {
        return alternateDirs;
    }

    /**
     * @return the repository being updated
     */
    @Nonnull
    public Repository getRepository() {
        return repository;
    }

    @Nonnull
    public String getObjectDir() {
        return objectDir;
    }

    @Nonnull
    public String getQuarantinePath() {
        return quarantinePath;
    }
}
