package info.bukova.isspst.ui.settings;

import info.bukova.isspst.data.UserSettingsData;
import info.bukova.isspst.services.users.UserService;
import info.bukova.isspst.storage.FileStorage;
import info.bukova.isspst.ui.DocumentViewModel;

import java.awt.image.RenderedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

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.Window;

public class UserSettingsVM extends DocumentViewModel
{
	@WireVariable
	private UserService userService;
	@WireVariable
	private FileStorage storage;
	private UserSettingsData settings;
	
	@Init(superclass = true)
	public void init() {
		settings = userService.getUserSettings();
	}

	public UserSettingsData getSettings() {
		return settings;
	}
	
	@Command
	@NotifyChange({"settings", "signatureImg"})
	public void uploadSignature(@ContextParam(ContextType.TRIGGER_EVENT) UploadEvent upEvent) {
		int i = upEvent.getMedia().getName().lastIndexOf(".");
		String fileName = "SignatureImageFile_" + userService.getCurrent().getUsername() + upEvent.getMedia().getName().substring(i);

		storage.saveFile(upEvent.getMedia().getByteData(), fileName);
		settings.setSignatureFile(fileName);
	}
	
	@Command
	@NotifyChange("signatureImg")
	public void removeSignature() {
		settings.setSignatureFile(null);
	}
	
	@Command
	public void save(@BindingParam("window") Window window) {
		userService.setUserSettings(settings);
		userService.update(userService.getCurrent());
		onClose();
		window.detach();
	}
	
	@Command
	public void onClose() {
		if (userService.getUserSettings().getSignatureFile() == null && settings.getSignatureFile() != null) {
			storage.removeFile(settings.getSignatureFile());
		}
	}
	
	public boolean isCanSave() {
		return true;
	}
	
	public RenderedImage getSignatureImg() {
		if (settings.getSignatureFile() == null || settings.getSignatureFile().isEmpty()) {
			return null;
		}
		
		try {
			return ImageIO.read(storage.file(settings.getSignatureFile()));
		} catch (IOException e) {
			return null;
		}
	}

}
