package com.acme.model.domain.ejf.dao;


import com.acme.model.domain.ejf.vo.PasswordTemplate;
import com.acme.structure.BaseEntity;
import com.acme.structure.dao.MainDao;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.Query;


public class EJFDao
{
    MainDao dao=null;
    
    public EJFDao()
    {
        dao=new MainDao();
    }
        
    public Collection findRolesForPrincipal(EntityManager manager, String principal)
    {
        StringBuilder queryString = new StringBuilder();
        queryString.append("SELECT r FROM User u \n")
                                .append("INNER JOIN u.userRoleGroups urg \n")
                                .append("INNER JOIN urg.roleGroup rg \n")
                                .append("INNER JOIN rg.roleGroupDetail rgd \n")
                                .append("INNER JOIN rgd.role r \n")
                                .append("WHERE u.username=:principal \n");
        Query query=manager.createQuery(queryString.toString());
        query.setParameter("principal", principal);

        return query.getResultList();
    }

    public int changeUserPassword(EntityManager manager, PasswordTemplate passwordTemplate, String principal) 
    {
        StringBuilder queryString = new StringBuilder();
        queryString.append("UPDATE User u \n")
                                .append("SET u.password=:newPassword \n")
                                .append("where u.username=:principal \n")
                                .append("and u.password=:oldPassword \n");
        
        Query query=manager.createQuery(queryString.toString());

        query.setParameter("newPassword", passwordTemplate.getNewPassword());
        query.setParameter("principal", principal);
        query.setParameter("oldPassword", passwordTemplate.getOldPassword());
        
        return query.executeUpdate();
                    
    }

    public Collection<BaseEntity> findRolesForList(EntityManager manager)
    {
        StringBuilder queryString = new StringBuilder();
        queryString.append("SELECT new com.acme.model.domain.ejf.entity.Role(r.id, r.roleName) \n").append("FROM Role r \n").append("ORDER BY r.roleName \n");

        Query query = manager.createQuery(queryString.toString());

        return query.getResultList();
    }

    public Collection<BaseEntity> findRoleGroupsForList(EntityManager manager)
    {
        StringBuilder queryString = new StringBuilder();
        queryString.append("SELECT new com.acme.model.domain.ejf.entity.RoleGroup(r.id, r.name) \n").append("FROM RoleGroup r \n").append("ORDER BY r.name \n");

        Query query = manager.createQuery(queryString.toString());

        return query.getResultList();
    }
}
