package my_tree;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.validation.ValidationException;

public class TUser  implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public String passw;
	public String name;
	public Boolean loged;
	
	@PostConstruct
	void init()
	{loged=false;}
	
	public String getPassw() {
		return passw;
	}
	public void setPassw(String passw) {
		this.passw = passw;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void validate(javax.faces.context.FacesContext context, javax.faces.component.UIComponent uic, java.lang.Object o)
	{
		String name = (String) o;
        if(name == null || name.length() < 3)
        {
            context.addMessage(null, new FacesMessage("Короткое имя пользователя"));
            //throw new ValidationException();
	    }
	}

	
	
	public Boolean getLoged() {
		return loged;
	}

	public void setLoged(Boolean loged) {
		this.loged = loged;
	}

	public void doLoging()
	{
		System.out.println("doLoging()");
		this.loged=new Boolean((this.name.equals("123")&&this.passw.equals("123")));
		System.out.println("this.loged="+this.loged);
		
	}
	public String doLogingStr()
	{
		System.out.println("doLogingStr()");
		ExternalContext k=FacesContext.getCurrentInstance().getExternalContext();
		
		Map<String, Object> cookieProps = new HashMap<String, Object>();
        cookieProps.put("maxAge", new Integer(365 * 24 * 60 * 60)); // 1 year as default
        cookieProps.put("path", FacesContext.getCurrentInstance()
                 .getExternalContext().getRequestServerName());
        
	    k.addResponseCookie("username",this.name, cookieProps);
	    System.out.println("this.name="+this.name+" this.passw="+this.passw);
	    if(null==this.name||this.name.isEmpty()||null==this.passw||this.passw.isEmpty()) {this.name="";this.passw="";return  "#";}
	      try{
		if((this.name.equals("123")&&this.passw.equals("123")))return "test.xhtml"; else return  "error.xhtml";
	      }catch(Exception e)
	      {
	    	  System.out.println("e="+e.toString());
	    	  return  "#";
	      }
		
	}
}
