package com.armundia.app.login;

import java.util.Date;
import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.armundia.core.users.admin.entity.SeUsersAccess;
import com.armundia.core.users.entity.SeUsers;

@ApplicationScoped
@SuppressWarnings({ "unchecked" })
public class LoginBroker {
	
	@PersistenceContext
	private EntityManager em;
	
	
	public SeUsers getUser(String userid) throws NoResultException, NonUniqueResultException {
		String strSQL = "select a from SeUsers a where UPPER(a.userid) = :userid";

		Query query = em.createQuery(strSQL);
		query.setParameter("userid", userid.toUpperCase());
		
		SeUsers user = (SeUsers) query.getSingleResult();
		
		return user;
	}
	
	public void updateAndPersistUser(SeUsers user) {
		em.merge(user);
		em.flush();
		em.detach(user);
	}
	
	public void insertUserAccess(String resultMessage, boolean resultStatus, String userid, String ipAddress, String userAgent, String clientVersion) {
		SeUsersAccess seUsersAccess = new SeUsersAccess();
		seUsersAccess.setUserId(userid);
		seUsersAccess.setResultMessage(resultMessage);
		seUsersAccess.setResultStatus(resultStatus);
		seUsersAccess.setDataLogin(new Date());
		
		seUsersAccess.setIpAddress(emptyStringNull(ipAddress));
		seUsersAccess.setUserAgent(emptyStringNull(userAgent));
		seUsersAccess.setClientVersion(emptyStringNull(clientVersion));

		em.persist(seUsersAccess);
	}
	
	public List<String> getAuthorizations(String userId) {
		String qStr = "SELECT " +
				"DISTINCT a.authid  " +
				"FROM UsersRoles ur , Roles r, RolesAuth ra , Authorization a " +
				"WHERE " +
				"ur.id.roleid = r.roleid " +
				"AND ra.id.roleid = r.roleid " +
				"AND a.authid = ra.id.authid " +
				"AND ur.id.userid = :username " +
				"ORDER BY a.authid ";

		Query query = em.createQuery(qStr);
		query.setParameter("username", userId);

		List<String> autorizzazioni = query.getResultList();

		return autorizzazioni;
	}
	
	public List<String> getRoles(String userId) {
		String qString = "select distinct(ur.id.roleid) from UsersRoles ur  where  ur.id.userid = :idUser ";
		
		Query query = em.createQuery(qString);
		query.setParameter("idUser", userId);

		List<String> ruoli = query.getResultList();

		return ruoli;
	}
	
	private String emptyStringNull(String string) {
		if (string == null || string.isEmpty()) {
			return null;
		}
		return string;
	}
}
