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

import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class ResolveCommitsStdioHandler extends AbstractBatchCheckCatFileStdioHandler<Map<String, String>> {

    private final Iterator<String> commitishes;
    private final Map<String, String> result;

    private String commitish; // the current commitish being resolved

    public ResolveCommitsStdioHandler(Set<String> commitishes) {
        this.commitishes = commitishes.iterator();

        result = new HashMap<>();
    }

    @Override
    public Map<String, String> getResult() {
        return result;
    }

    @Override
    protected String getNextObjectId() {
        if (commitishes.hasNext()) {
            commitish = commitishes.next();
            return StringUtils.appendIfMissing(commitish, "^{}"); // to fully peel any tag object
        }
        return null;
    }

    @Override
    protected void onMissing(@Nonnull String objectId) {
        // don't return missing objects; simply move on to the next object
        commitish = null;
    }

    @Override
    protected void onObject(@Nonnull BatchHeader header) {
        String objectId = header.getObjectId();
        String type = header.getType();
        if ("commit".equals(type)) {
            result.put(commitish, objectId);
        }
        // for any other type; the commit-ish could not be resolved into a commit, so don't include it in the results
    }
}
