package info.bukova.isspst.ui;

import info.bukova.isspst.data.DataModel;
import info.bukova.isspst.data.FileMetainfo;
import info.bukova.isspst.storage.DocumentFileStorage;
import info.bukova.isspst.storage.EntityWithAttachment;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Filedownload;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Pepa Rokos
 */
public class FormWithUpload<T extends DataModel> extends FormViewModel<T> {

	private List<FileMetainfo> attachments;
	private List<FileMetainfo> forDelete;
	@WireVariable
	private DocumentFileStorage documentStorage;

	@Init(superclass = true)
	public void initFormWithUpload() {
		if (getDataBean() instanceof EntityWithAttachment) {
			attachments = ((EntityWithAttachment)getDataBean()).getAttachedFiles();
		}
		forDelete = new ArrayList<FileMetainfo>(); // kolekce příloh na smazání v případě uložení záznamu
	}

	@Command
	@NotifyChange("attachments")
	public void uploadAttachment(@ContextParam(ContextType.TRIGGER_EVENT) UploadEvent upEvent) {
		FileMetainfo metaInfo = documentStorage.saveAndCreateInfo(upEvent.getMedia().getByteData(),
				upEvent.getMedia().getName());

		((EntityWithAttachment)getDataBean()).addAttachment(metaInfo);
	}

	@Command
	@NotifyChange("attachments")
	public void deleteAttachment(@BindingParam("attachment") FileMetainfo metaInfo) {
		((EntityWithAttachment)getDataBean()).removeAttachment(metaInfo);
		forDelete.add(metaInfo); // smazat až v případě uložení záznamu
	}

	@Command
	public void downloadAttachment(@BindingParam("attachment") FileMetainfo metaInfo) {
		Filedownload.save(documentStorage.fileData(metaInfo), metaInfo.getContentType(), metaInfo.getFileName());
	}

	public List<FileMetainfo> getAttachments() {
		return attachments;
	}

	@Override
	protected void doSave() {
		maintainAttachment();
		super.doSave();
	}

	protected void maintainAttachment() {
		for (FileMetainfo info : forDelete) {
			documentStorage.removeFile(info);
		}
	}

}
