package ru.yandex.webmaster3.worker.digest.graphics.draw;

import NWebmaster.proto.digest.Digest;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.webmaster3.core.digest.graphics.draw.ChartSettings;
import ru.yandex.webmaster3.core.digest.graphics.draw.DrawGraphUtil;
import ru.yandex.webmaster3.core.digest.graphics.draw.data.PointLong;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * Created by ifilippov5 on 17.09.17.
 */
public class BuildClicksGraphicsUtil {
    private static final Logger log = LoggerFactory.getLogger(BuildClicksGraphicsUtil.class);

    public static byte[] process(List<Digest.ClicksByPeriod> pastSeries, List<Digest.ClicksByPeriod> currentSeries, ChartSettings chartSettings) {
        try {
            String chartSvg = DrawGraphUtil.draw(clicksToPoint(pastSeries), clicksToPoint(currentSeries), chartSettings);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            write(chartSvg, out);
            return out.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static List<PointLong> clicksToPoint(List<Digest.ClicksByPeriod> clicks) {
        List<PointLong> points = new ArrayList<>();
        int day = 0;
        for (Digest.ClicksByPeriod dayClicks : clicks) {
            points.add(new PointLong(day++, dayClicks.getClicks()));
        }
        return points;
    }

    private static void write(String svg, OutputStream os) throws Exception {
        TranscoderInput input = new TranscoderInput(new StringReader(svg));
        PNGTranscoder transcoder = new PNGTranscoder();
        TranscoderOutput out = new TranscoderOutput(os);
        transcoder.transcode(input, out);
    }

    private static byte[] encodeBase64(byte[] source) {
        return Base64.getEncoder().encode(source);
    }
}
