package com.k_int.ciim.json;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.springframework.stereotype.Component;

import com.k_int.ciim.ref.Constants;
import com.k_int.svc.identity.datamodel.RegisteredUserHDO;
import com.k_int.svc.identity.datamodel.RoleHDO;
import com.sun.jersey.api.view.ImplicitProduces;

@XmlRootElement
@ImplicitProduces("application/json;qs=5")
@XmlAccessorType(XmlAccessType.FIELD)
@Component
public class CIIMUserJSON 
{
	public Long id;
	public String username;
	public String display_name;
	public String password;
	public String email;
	public List<String> roles;
	public Boolean active;
	public String last_login;
	public String registered_date;
	
	@XmlTransient
	public SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy '<I>'HH:mm:ss'</I>'");
	  
	public CIIMUserJSON()
	{
		
	}
	
	public CIIMUserJSON( 	Long id,
							String username,
							String display_name,
							String password,
							String email,
							List<String> roles,
							Boolean active,
							Date last_login,
							Date registered_date)
	{
		this.id = id;
		this.username = username;
		this.display_name = display_name;
		this.password = password;
		this.email = email;
		this.roles = roles;
		this.active = active;
		
		if(last_login != null)
		{
			this.last_login = format.format(last_login);
		}
		if(registered_date != null)
		{
			this.registered_date = format.format(registered_date);
		}
	}
	
	public static CIIMUserJSON userHDOtoDTO(RegisteredUserHDO hdo, String username, String password) 
	{		  	  
		return new CIIMUserJSON( 	hdo.getId(),
	    							username,
	    							hdo.getName(),
	    							password,
	    							hdo.getPrimaryEmail(),
	    							userRoles(hdo),
	    							hdo.getActive(),
	    							hdo.getLastLogin(),
	    							hdo.getDateRegistered());
	}
	
	private static List<String> userRoles(RegisteredUserHDO hdo)
	{
		List<String> lReturn = new ArrayList<String>();
	  
		Set<RoleHDO> lRoles = hdo.getRoles();
	  
		if(lRoles != null && lRoles.size() > 0)
		{
			for(RoleHDO lRole : lRoles)
			{
				if(lRole != null)
				{
					lReturn.add(lRole.toString().replace(Constants.CIIM_ROLE_PREFIX, ""));
				}
			}
		}
	  
		return lReturn;
	}
}
