package sn.unitech.stock.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import sn.unitech.stock.dao.iface.ISysUsersDao;
import sn.unitech.stock.entity.SysAccessUser;
import sn.unitech.stock.entity.SysAccessUserId;
import sn.unitech.stock.entity.SysAdherent;
import sn.unitech.stock.entity.SysMenu;
import sn.unitech.stock.entity.SysUsers;
import sn.unitech.stock.modal.Resultat;
public class SysUsersDao extends DataAccess implements ISysUsersDao{
public SysUsersDao() {
// TODO Auto-generated constructor stub
}
@SuppressWarnings("unchecked")
public boolean saveUser(SysUsers user) {
EntityManager em=getEntityManager();
EntityTransaction tx = em.getTransaction();
try{
tx.begin();
user.setSysAdherent(em.find(SysAdherent.class, user.getId().getIdAdherent()));
user.setPasswd(ToolsDao.getToolsDao().encodePassword(user.getId().getIdUser()));
user.setSysDatcre(new java.util.Date());
persist(user, em);
tx.commit();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}finally{
em.close();
}
}
@Override
public Resultat updateUser(List<SysMenu> listMenu,SysUsers user){
try{
EntityManager em=this.getEntityManager();
EntityTransaction tx=em.getTransaction();
tx.begin();
SysUsers sysUsers;
Object obj=this.find(SysUsers.class, user.getId(), em);
if(obj==null){
user.setSysAdherent(em.find(SysAdherent.class, user.getId().getIdAdherent()));
user.setPasswd(ToolsDao.getToolsDao().encodePassword(user.getId().getIdUser()));
user.setSysDatcre(new java.util.Date());
sysUsers=user;
persist(user, em);
this.persist(sysUsers, em);
}
else{
sysUsers=(SysUsers) obj;
sysUsers.setNom(user.getNom());
sysUsers.setPrenom(user.getPrenom());
sysUsers.setIsActiv(user.getIsActiv());
persist(sysUsers,em);
}
for(SysMenu menu:listMenu){
SysAccessUserId sysAccessUserId = new SysAccessUserId();
sysAccessUserId.setIdAdherent(user.getId().getIdAdherent());
sysAccessUserId.setIdUser(user.getId().getIdUser());
sysAccessUserId.setIdMenu(menu.getIdMenu());
SysAccessUser sysAccessUser=(SysAccessUser) this.find(SysAccessUser.class, sysAccessUserId, em);
if(sysAccessUser!=null)sysAccessUser.setIsAccept(menu.isSelected()?"True":"False");
if(sysAccessUser==null) sysAccessUser=new SysAccessUser(sysAccessUserId,menu,sysUsers,menu.isSelected()?"True":"False");
persist(sysAccessUser, em);
}
tx.commit();
return new Resultat(true,"Validation effectuee avec succes");
}catch(Exception e){
e.printStackTrace();
return new Resultat(false," Fatal error "+e.getMessage());
}
}
}