package com.atlassian.stash.internal.scm.git.command.lsfiles;

import com.atlassian.bitbucket.content.SimplePath;
import com.atlassian.bitbucket.io.LineReader;
import com.atlassian.bitbucket.io.LineReaderOutputHandler;
import com.atlassian.bitbucket.scm.CommandOutputHandler;
import com.atlassian.bitbucket.scm.git.GitUtils;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StagedLsFilesOutputHandler extends LineReaderOutputHandler implements CommandOutputHandler<List<StagedFile>> {

    private static final Pattern LS_FILES_PATTERN = Pattern.compile("(\\d+) ([0-9a-fA-F]{40}) (\\d)\\t(.*)");
    private static final int GROUP_CONTENT_ID = 2;
    private static final int GROUP_STAGE = 3;
    private static final int GROUP_PATH = 4;

    private final List<StagedFile> stagedFiles = Lists.newArrayList();

    public StagedLsFilesOutputHandler() {
        super(StandardCharsets.UTF_8);
    }

    @Override
    public List<StagedFile> getOutput() {
        return stagedFiles;
    }

    @Override
    protected void processReader(LineReader reader) throws IOException {
        String line;
        while ((line = resetWatchdogAndReadLine(reader)) != null) {
            Matcher matcher = LS_FILES_PATTERN.matcher(line);
            if (matcher.matches()) {
                int stageNumber = Integer.parseInt(matcher.group(GROUP_STAGE));
                stagedFiles.add(new StagedFile(matcher.group(GROUP_CONTENT_ID),
                        new SimplePath(GitUtils.unescapeQuoted(matcher.group(GROUP_PATH))), stageNumber));
            }
        }
    }
}
