package org.yacos.core.conferences;

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

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.yacos.core.users.Role;
import org.yacos.core.users.User;
import org.yacos.core.users.UserManagerBean;


@Stateless
public class ConferenceManagerBean implements IConferenceManager {
	@PersistenceContext
    EntityManager em;

	public Conference addConference(String titre, String descirption, String infoComplementray, Date dataAbstract, Date dateArticle, Date dateEvaluation, Date dateStart, Date dateEnd) {
		Conference conf = new Conference(titre, descirption, infoComplementray, dataAbstract, dateArticle, dateEvaluation, dateStart, dateEnd);
		em.persist(conf);
		return conf;
	}

	public Conference getConference(Integer id) {
		 return em.find(Conference.class, id);
	}

	public void remove(Conference conf) {
		Conference persistedConf = em.find(Conference.class, conf.getId());
		em.remove(persistedConf);
	}

	public void update(Conference conf) {
		em.merge(conf);
	}

	@SuppressWarnings("unchecked")
	public List<Conference> getConferences() {
		 return em.createQuery("from Conference conf ORDER BY conf.id").getResultList();
	}
	
	public List<Conference> getConferences(User user){
		List<Conference> list = new ArrayList<Conference>();
		List<Role> tmpList = new UserManagerBean().getRoles();
		
		Conference conf;
		for (Role role : tmpList) {
			conf = role.getConference();
			if(!list.contains(conf)){
				list.add(conf);
			}
		}
		return list;
	}
	
	
	/* 
	 * 
	 * méthodes relatives aux roles
	 * */
	
	public void addRole(Role.RoleType roleType, User user, Conference conf) {
		Role role = new Role(roleType, user, conf);
		em.persist(role);
	}

	public void removeRole(Role role) {
		em.remove(role);
	}

	public void updateRole(Role role){
		em.merge(role);
	}
	
	public List<Role> getRoles(){
		return em.createQuery("from Role role").getResultList();
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Role> getRoles(User user, Conference conf) {
		 Query query = em.createQuery("from Role role where conference = ? and user = ?");
		 query.setParameter(1, conf);
		 query.setParameter(2, user);
		 		
		return query.getResultList();
	}
	

}
