package de.jottyfan.camporganizer.module.admin.model;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Base64;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import de.jottyfan.camporganizer.db.jooq.enums.EnumCamprole;
import de.jottyfan.camporganizer.db.jooq.enums.EnumDocument;
import de.jottyfan.camporganizer.db.jooq.enums.EnumFiletype;

/**
 *
 * @author jotty
 *
 */
public class DocumentBean implements Serializable{

	private static final long serialVersionUID = 1L;

	private Integer pk;
	@NotNull
	private EnumDocument doctype;
	@NotBlank
	private String name;
	private String document;
	@NotNull
	private EnumFiletype filetype;
	@NotNull
	private MultipartFile uploadfile;
	private EnumCamprole[] roles;

	/**
	 * convert the uploadfile to the document
	 *
	 * @throws IOException on IO errors
	 */
	public void encodeUpload() throws IOException {
		if (uploadfile != null) {
			InputStream inputStream = uploadfile.getInputStream();
			byte[] bytes = IOUtils.toByteArray(inputStream);
			if (bytes.length > 0) {
				document = Base64.getEncoder().encodeToString(bytes);
			} // not uploaded files should not be changed, so document must be kept as is
		}
	}

	@Override
	public String toString() {
		StringBuilder buf = new StringBuilder();
		buf.append(name).append(".").append(filetype);
		return buf.toString();
	}

	public Integer getPk() {
		return pk;
	}

	public void setDoctype(EnumDocument doctype) {
		this.doctype = doctype;
	}

	public EnumDocument getDoctype() {
		return doctype;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setDocument(String document) {
		this.document = document;
	}

	public String getDocument() {
		return document;
	}

	public void setFiletype(EnumFiletype filetype) {
		this.filetype = filetype;
	}

	public EnumFiletype getFiletype() {
		return filetype;
	}

	public MultipartFile getUploadfile() {
		return uploadfile;
	}

	public void setUploadfile(MultipartFile uploadfile) {
		this.uploadfile = uploadfile;
	}

	public EnumCamprole[] getRoles() {
		return roles;
	}

	public void setRoles(EnumCamprole[] roles) {
		this.roles = roles;
	}

	/**
	 * @param pk the pk to set
	 */
	public void setPk(Integer pk) {
		this.pk = pk;
	}
}
