package info.bukova.isspst.ui.users;

import info.bukova.isspst.data.User;
import info.bukova.isspst.services.users.RoleService;
import info.bukova.isspst.services.users.UserService;
import info.bukova.isspst.ui.FormViewModel;
import info.bukova.isspst.validators.UserFormValidator;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.zkoss.bind.Validator;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.select.annotation.WireVariable;

public class UserForm extends FormViewModel<User>
{
	@WireVariable
	private RoleService roleService;
	@WireVariable
	private UserService userService;
	private String retPasswd = "";
	private String password = "";
	private UserRoles userRoles;
	private boolean loginFree;

	private Validator userFormValidator;

	@Init(superclass = true)
	public void init()
	{
		userRoles = new UserRoles(getDataBean(), roleService.getAll());
		loginFree = true;
		this.setUserFormValidator(new UserFormValidator(getDataBean().getCreated() == null));
	}

	public UserRoles getUserRoles()
	{
		return userRoles;
	}

	public String getRetPasswd()
	{
		return retPasswd;
	}

	public void setRetPasswd(String retPasswd)
	{
		this.retPasswd = retPasswd;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	@Command
	@NotifyChange({ "loginFree", "canSave" })
	public void checkLogin()
	{
		try
		{
			userService.loadUserByUsername(getDataBean().getUsername());
			loginFree = false;
		} catch (UsernameNotFoundException e)
		{
			loginFree = true;
		}
	}

	public boolean isLoginFree()
	{
		return loginFree || this.isEditRec();
	}

	@Override
	protected void doSave()
	{
		userService.saveWithPwd(getDataBean(), this.password);
	}

	@Override
	protected void doAdd()
	{
		userService.setPassword(getDataBean(), password);
		userService.add(getDataBean());
	}

	@Override
	public boolean isCanSave()
	{
		return isLoginFree() && getDataBean().getUsername() != null && !getDataBean().getUsername().isEmpty();
	}

	public Validator getUserFormValidator()
	{
		return userFormValidator;
	}

	public void setUserFormValidator(Validator userFormValidator)
	{
		this.userFormValidator = userFormValidator;
	}
}
