package de.oaa.xxx.registration;

import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.annotation.Resource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.UserTransaction;

@ApplicationScoped
public class RegistrationDAO {

	private Logger LOGGER = LoggerFactory.getLogger(getClass());

	@PersistenceContext(name = "registration")
	private EntityManager entityManager;
	@Resource
	private UserTransaction transaction;

	public List<RegistrationEntity> findByEmail(String email) {
		TypedQuery<RegistrationEntity> query = entityManager
				.createQuery("select r from RegistrationEntity r where r.email = :email", RegistrationEntity.class);
		query.setParameter("email", email);
		return query.getResultList();
	}

	public List<RegistrationEntity> findByName(String name) {
		TypedQuery<RegistrationEntity> query = entityManager
				.createQuery("select r from RegistrationEntity r where r.name = :name", RegistrationEntity.class);
		query.setParameter("name", name);
		return query.getResultList();
	}

	public void update(RegistrationEntity toUpdate) {
		try {
			transaction.begin();
			entityManager.merge(toUpdate);
			transaction.commit();
		} catch (NotSupportedException | SystemException | SecurityException | IllegalStateException | RollbackException
				| HeuristicMixedException | HeuristicRollbackException e) {
			e.printStackTrace();
		}
	}

	public void persist(RegistrationEntity toPersist) {
		try {
			transaction.begin();
			LOGGER.info("Persisting Entity " + toPersist);
			entityManager.persist(toPersist);
			transaction.commit();
		} catch (NotSupportedException | SystemException | SecurityException | IllegalStateException | RollbackException
				| HeuristicMixedException | HeuristicRollbackException e) {
			e.printStackTrace();
		}
	}

	public void remove(RegistrationEntity toRemove) {
		try {
			transaction.begin();
			entityManager.remove(toRemove);
			transaction.commit();
		} catch (NotSupportedException | SystemException | SecurityException | IllegalStateException | RollbackException
				| HeuristicMixedException | HeuristicRollbackException e) {
			e.printStackTrace();
		}
	}
	
	public RegistrationEntity findById(UUID id) {
		return entityManager.find(RegistrationEntity.class, id);
	}
}
