package de.oaa.xxx.framework;

import java.util.Collections;
import java.util.List;

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

import jakarta.persistence.EntityManager;

public abstract class AbstractDAO<T extends XXXEntity> {

	private Logger LOGGER = LoggerFactory.getLogger(getClass());
	private Class<T> entityClass;
	private EntityManager entityManager;
	
	public AbstractDAO(Class<T> entityClass, EntityManager entityManager) {
		this.entityClass = entityClass;
		this.entityManager = entityManager;
	}
	
	public void update(T toUpdate) {
		try {
			getEntityManager().merge(toUpdate);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	public void persist(T toPersist) {
		try {
			LOGGER.info("Persisting Entity " + toPersist);
			getEntityManager().persist(toPersist);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	public void remove(T toRemove) {
		try {
			getEntityManager().remove(toRemove);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}
	
	public T findById(Object id) {
		try {
			return getEntityManager().find(entityClass, id);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			return null;
		}
	}
	
	public List<T> list() {
		try {			
			return getEntityManager().createQuery("select e from " + entityClass.getSimpleName() + " e", entityClass).getResultList();
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			return Collections.emptyList();
		}
	}
	
	protected EntityManager getEntityManager() {
		return entityManager;
	}
}
