package de.ivu.elect.business.image.entity;

import java.io.ByteArrayInputStream;
import java.util.Base64;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;

/**
 *  on 01.12.2015.
 *
 *
 */
public abstract class AbstractBild implements BildBase {

  /**
   * http://stackoverflow.com/questions/10073905/display-database-blob-images-in-pgraphicimage-inside-uirepeat
   */
  public DefaultStreamedContent getStreamedContent() {
    FacesContext context = FacesContext.getCurrentInstance();
    if (StringUtils.isEmpty(getContentBase64()) || PhaseId.RENDER_RESPONSE.equals(context.getCurrentPhaseId())) {
      return new DefaultStreamedContent();
    }

    DefaultStreamedContent defaultStreamedContent = new DefaultStreamedContent(new ByteArrayInputStream(Base64.getDecoder().decode(getContentBase64())), getMimeType());
    return defaultStreamedContent;
  }

  public void setContent(byte[] content){
    setContentBase64(Base64.getEncoder().encodeToString(content));
  }
}
