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

import com.atlassian.bitbucket.mesh.git.ref.Branch;

import javax.annotation.Nonnull;

import static java.util.Objects.requireNonNull;

/**
 * A reusable component for parsing {@link Branch branches} from a {@code String}.
 */
public class ForEachBranchParser implements ForEachRefParser<Branch> {

    /**
     * Format for {@code git for-each-ref}. This is the format that is expected by {@link #parse(String)}.
     * <ul>
     *     <li>{@code refname} -&gt; fully qualified branch name (ID)</li>
     *     <li>{@code objectname} -&gt; commit hash</li>
     * </ul>
     *
     * @see <a href="http://git-scm.com/docs/git-for-each-ref/2.2.0">git-for-each-ref</a>
     */
    public static final String FORMAT = ForEachRefUtils.normalize("%(refname)|%(objectname)");

    private final String head;

    public ForEachBranchParser(@Nonnull String head) {
        this.head = requireNonNull(head, "head");
    }

    @Nonnull
    @Override
    public String getFormat() {
        return FORMAT;
    }

    /**
     * Parses a string and returns a {@link Branch}.
     *
     * @param line a single line of output from {@code git for-each-ref}
     * @return a {@link Branch}, or {@code null} if the line could not be parsed
     */
    @Override
    public Branch parse(@Nonnull String line) {
        String[] pieces = line.split(ForEachRefUtils.SEPARATOR_CHAR);
        if (pieces.length == 2) {
            String id = pieces[0];

            return new Branch.Builder()
                    .id(id)
                    .isDefault(head.equals(id))
                    .latestCommit(pieces[1])
                    .build();
        }

        return null;
    }
}
