package de.ivu.elect.presentation.gruppe;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.inject.Named;

import de.ivu.elect.business.gruppe.entity.Gruppe;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.file.UploadedFile;

import de.ivu.elect.business.image.entity.Bild;

/**
 * SessionScoped, damit Zugriff auf StreamedContent funktioniert
 */
@SessionScoped
@Named(GruppeLogoSession.COMPONENT_NAME)
public class GruppeLogoSession implements Serializable {

  public static final String COMPONENT_NAME = "gruppeLogoSession";

  private UploadedFile uploadedFile;

  private Bild logo;

  public void init(Bild logo) {
    this.logo = logo;
  }

  public void reset() {
    logo = null;
    uploadedFile = null;
  }

  public UploadedFile getUploadedFile() {
    return uploadedFile;
  }

  public void setUploadedFile(UploadedFile uploadedFile) {
    this.uploadedFile = uploadedFile;
  }

  public StreamedContent getUploadedPreview() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    if (uploadedFile == null || PhaseId.RENDER_RESPONSE.equals(context.getCurrentPhaseId())) {
      return new DefaultStreamedContent();
    }
    return DefaultStreamedContent.builder()
        .stream(() -> new ByteArrayInputStream(uploadedFile.getContent()))
        .contentType(uploadedFile.getContentType())
        .build();
  }

  public StreamedContent getLogoPreview() throws IOException {
    if (isLogoVorhanden()) {
      return logo.getStreamedContent();
    }
    return new DefaultStreamedContent();
  }

  public boolean isLogoVorhanden() {
    return logo != null;
  }

  public Bild getLogo() {
    return logo;
  }

  public void setLogo(Bild logo) {
    this.logo = logo;
  }

  public void setLogoVonGruppe(Gruppe gruppe) {
    if (gruppe == null || gruppe.getLogo() == null) {
      setLogo(null);
    } else {
      Bild logo = gruppe.getLogo();
      logo.setGrupppeNameFuerDateiname(gruppe.getKurzname());
      setLogo(logo);
    }
  }
}
