package com.atlassian.bitbucket.io;

import com.atlassian.bitbucket.scm.CommandInputHandler;
import com.atlassian.utils.process.BaseInputHandler;
import com.atlassian.utils.process.IOUtils;

import java.io.*;

/**
 * Simple InputHandler that writes a sequence of lines to the process input.
 */
public class LineInputHandler extends BaseInputHandler implements CommandInputHandler {

    private final Iterable<String> lines;

    public LineInputHandler(Iterable<String> lines) {
        this.lines = lines;
    }

    @Override
    public void process(OutputStream input) {
        // write all lines to the input stream
        Writer writer = new OutputStreamWriter(input);
        try {
            if (lines != null) {
                for (String line : lines) {
                    writer.write(line + "\n");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }
}
