package tutorial.core.repositories.jpa;

import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import tutorial.core.models.entities.EmailDomain;
import tutorial.core.repositories.EmailDomainRepo;

/**
 * 
 * @author Xavier
 */
@Repository
public class JpaEmailDomainRepo implements EmailDomainRepo {
    @PersistenceContext
    private EntityManager em;

    @Override
    public EmailDomain createEmailDomain(EmailDomain data) {
        em.persist(data);
        return data;
    }

    @Override
    public List<EmailDomain> findAllEmailDomains() {
        Query query = em.createQuery("SELECT b from EmailDomain b");
        return query.getResultList();
    }

    @Override
    public EmailDomain findEmailDomain(Long id) {
        return em.find(EmailDomain.class, id);
    }
    
    @Override
    public EmailDomain findEmailDomainByName(String name) {
        Query query = em.createQuery("SELECT b from EmailDomain b where b.emailDomainText = :name");
        query.setParameter("name", name);
        List<EmailDomain> emailDomains = query.getResultList();
        if(emailDomains.isEmpty()) {
            return null;
        } else {
            return emailDomains.get(0);
        }
    }

    @Override
    public void deleteAllEmailDomains() {
        Query query = em.createQuery("DELETE from EmailDomain");
        int numDeletedMails = query.executeUpdate();
    }
}
