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

import com.atlassian.bitbucket.mesh.git.content.Blame;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;

public class IncrementalBlameStdioHandler extends AbstractBlameStdioHandler<List<Blame>> {

    private final List<Span> spans;

    private Span span;

    public IncrementalBlameStdioHandler() {
        spans = new ArrayList<>();
    }

    @Override
    public List<Blame> getResult() {
        return generateBlame(spans);
    }

    @Override
    protected boolean onStdout(@Nonnull String line, boolean truncated) {
        Matcher matcher = SPAN_HEADER_PATTERN.matcher(line);
        if (matcher.matches()) {
            //If we find a span header, we create a new Span. It will take multiple lines to
            //assemble, which is handled by readCommit below
            span = createSpan(matcher);
        } else if (span == null) {
            throw new IllegalStateException("Line [" + line + "] is not a valid span");
        } else if (readCommit(span.getHash(), line)) {
            //readCommit returns true when it finds the "filename" line, which is the last
            //property necessary to assemble the span
            spans.add(span);
            span = null;
        }

        return true;
    }

    @Override
    protected void onStdoutClosed() {
        Collections.sort(spans);
    }
}
