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

import com.atlassian.bitbucket.mesh.git.GitNodeType;
import com.atlassian.bitbucket.mesh.git.exception.PathNotFoundException;
import com.atlassian.bitbucket.mesh.process.handler.AbstractLineStdioHandler;
import com.atlassian.bitbucket.mesh.process.handler.LineDecoder;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.nio.charset.StandardCharsets;

import static java.util.Objects.requireNonNull;

public class TypeLsTreeStdioHandler extends AbstractLineStdioHandler<GitNodeType> {

    private final String commitId;
    private final String path;

    private String type;

    public TypeLsTreeStdioHandler(@Nonnull String commitId, @Nonnull String path) {
        //Mode (6) + sp (1) + "blob|commit|tree" (6) + sp (1) = 14
        //This ensures we get the type and the space after it even if it's "commit"
        super(StandardCharsets.UTF_8, LineDecoder.Mode.NULL, 14);

        this.commitId = requireNonNull(commitId, "commitId");
        this.path = requireNonNull(path, "path");
    }

    @Nonnull
    @Override
    public GitNodeType getResult() {
        if (type == null) {
            throw new PathNotFoundException(commitId, path);
        }

        return GitNodeType.fromType(type);
    }

    @Override
    protected boolean onStdout(@Nonnull String line, boolean truncated) {
        if (StringUtils.isNotEmpty(line)) {
            String[] pieces = line.split(" ");
            type = pieces[1];
        }

        //No matter what, we get all the output we want to handle on the first line
        return false;
    }
}