package ru.yandex.webmaster3.core.download.searchquery;

import com.opencsv.CSVWriter;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ifilippov5 on 06.03.17.
 */
public class CsvWriter implements AbstractWriter {
    private static final Logger log = LoggerFactory.getLogger(CsvWriter.class);
    private ByteArrayOutputStream out;
    private CSVWriter csvWriter;

    public CsvWriter() {
        out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out);
        csvWriter = new CSVWriter(writer);
    }

    @Override
    public void write(List<Object> line) {
        log.debug("Csv writer write data {} length", line.size());
        List<String> strings = line.stream().map(CsvWriter::formatValue).collect(Collectors.toList());
        csvWriter.writeNext(strings.toArray(ArrayUtils.EMPTY_STRING_ARRAY));
    }

    @Override
    public byte[] getBytes() {
        return out.toByteArray();
    }

    @Override
    public void close() throws IOException {
        csvWriter.close();
    }

    private static String formatValue(Object value) {
        if (value == null) {
            return "";
        }
        if (value instanceof Double || value instanceof Float) {
            return String.format("%.2f", value);
        }
        return value.toString();
    }
}
