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

import com.atlassian.bitbucket.io.LineReader;
import com.atlassian.bitbucket.io.LineReaderOutputHandler;
import com.atlassian.bitbucket.scm.CommandSummary;
import com.atlassian.bitbucket.scm.CommandSummaryHandler;
import com.atlassian.utils.process.ProcessException;

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

/**
 * @since 4.6
 */
public class CallbackForEachRefOutputHandler
        extends LineReaderOutputHandler
        implements ForEachRefOutputHandler<Void>, CommandSummaryHandler {

    private final ForEachRefCallback callback;

    public CallbackForEachRefOutputHandler(ForEachRefCallback callback) {
        super(StandardCharsets.UTF_8);

        this.callback = callback;
    }

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

    @Override
    public Void getOutput() {
        return null;
    }

    @Override
    public void onComplete(@Nonnull CommandSummary summary) throws ProcessException {
        try {
            callback.onComplete(summary);
        } catch (IOException e) {
            throw new ProcessException(e);
        }
    }

    @Override
    protected void processReader(LineReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            if (!callback.onLine(line)) {
                cancelProcess();

                break;
            }
        }
    }
}
