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

import com.atlassian.bitbucket.mesh.process.handler.AbstractProcessStdioHandler;
import com.atlassian.bitbucket.mesh.util.Version;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VersionStdioHandler extends AbstractProcessStdioHandler<Version> {

    public static final Pattern PATTERN_VERSION = Pattern.compile("^git version (.*)");

    private Version version;

    @Override
    public Version getResult() {
        return version;
    }

    @Override
    public void onStdout(@Nonnull ByteBuffer buffer, boolean closed) {
        if (version == null) {
            String stdout = StringUtils.chomp(StandardCharsets.UTF_8.decode(buffer).toString());

            Matcher matcher = PATTERN_VERSION.matcher(stdout);
            if (matcher.matches()) {
                version = new Version(matcher.group(1));
            }
        }
    }
}