package info.bukova.isspst.ui.users;

import info.bukova.isspst.data.User;
import info.bukova.isspst.services.users.UserService;
import info.bukova.isspst.ui.DocumentViewModel;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

public class PasswdVM extends DocumentViewModel
{
	
	private String oldPw;
	private String newPw;
	private String retPw;
	private User user;
	@WireVariable
	private UserService userService;
	
	@Init(superclass = true)
	public void init() {
		user = userService.getCurrent();
	}
	
	@Command
	public void save(@BindingParam("window") Window window) {
		if (!canSave()) {
			return;
		}
		
		userService.saveWithPwd(user, newPw);
		Messagebox.show("Heslo bylo změněno", "Změna hesla", Messagebox.OK, Messagebox.INFORMATION);
		window.detach();
	}
	
	private boolean canSave() {
		if (!user.getPassword().equals(userService.encodePassword(user, oldPw))) {
			Messagebox.show("Špatné staré heslo", "Chyba", Messagebox.OK, Messagebox.ERROR);
			return false;
		}
		
		if (newPw == null || newPw.isEmpty()) {
			Messagebox.show("Zadejte nové heslo", "Chyba", Messagebox.OK, Messagebox.ERROR);
			return false;
		}
		
		if (!newPw.equals(retPw)) {
			Messagebox.show("Nasouhlasí nová hesla", "Chyba", Messagebox.OK, Messagebox.ERROR);
			return false;
		}
		
		return true;
	}

	public String getOldPw() {
		return oldPw;
	}

	public void setOldPw(String oldPw) {
		this.oldPw = oldPw;
	}

	public String getNewPw() {
		return newPw;
	}

	public void setNewPw(String newPw) {
		this.newPw = newPw;
	}

	public String getRetPw() {
		return retPw;
	}

	public void setRetPw(String retPw) {
		this.retPw = retPw;
	}
	
	

}
