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

import com.atlassian.bitbucket.mesh.git.GitObjectInfo;
import com.atlassian.bitbucket.mesh.git.GitObjectType;
import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;
import java.util.*;

import static java.util.Objects.requireNonNull;

public class InfoBatchCheckCatFilesStdioHandler extends AbstractBatchCheckCatFileStdioHandler<Map<String, GitObjectInfo>> {

    private final ImmutableMap.Builder<String, GitObjectInfo> builder;
    private final Iterator<String> inputs;

    private String input; // the current input being resolved

    public InfoBatchCheckCatFilesStdioHandler(@Nonnull Collection<String> inputs) {
        this.inputs = requireNonNull(inputs, "inputs").iterator();

        builder = ImmutableMap.builder();
    }

    @Nonnull
    @Override
    public Map<String, GitObjectInfo> getResult() {
        return builder.build();
    }

    @Override
    protected String getNextObjectId() {
        if (inputs.hasNext()) {
            input = inputs.next();
            return input;
        }
        return null;
    }

    @Override
    protected void onMissing(@Nonnull String objectId) {
        input = null;
    }

    @Override
    protected void onObject(@Nonnull BatchHeader header) {
        builder.put(input, new GitObjectInfo(header.getObjectId(), header.getSize(),
                GitObjectType.fromObjectType(header.getType())));
    }
}
