package de.ivu.elect.jee.presentation.charts;

import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.enterprise.context.RequestScoped;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.inject.Named;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.primefaces.util.Constants;

@RequestScoped
@Named(ChartExport.COMPONENT_NAME)
public class ChartExport implements Serializable {

  public static final String COMPONENT_NAME = "chartExport";

  private String chartBase64;

  public String getChartBase64() {
    return chartBase64;
  }

  public void setChartBase64(String chartBase64) {
    this.chartBase64 = chartBase64;
  }

  public void exportChart() {
    if (chartBase64 != null && chartBase64.split(",").length > 1) {
      try {
        String encoded = chartBase64.split(",")[1];
        byte[] decoded = Base64.getDecoder().decode(encoded.getBytes(StandardCharsets.UTF_8));
        RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));

        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        String contentDispositionValue = "attachment";

        response.setContentType("image/png");
        response.setHeader("Content-Disposition", contentDispositionValue + ";filename=\"ergebnis.png\"");
        // WASDE-2161 response.addCookie(new Cookie(Constants.DOWNLOAD_COOKIE, "true"));

        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(renderedImage, "png", outputStream);
        response.setStatus(HttpServletResponse.SC_OK);
        response.getOutputStream().flush();
        facesContext.responseComplete();

      } catch (Exception e) {
        throw new FacesException(e);
      }
    }

  }
}
