package DAO;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;
import jpa.EntityManagerHelper;

import java.io.Serializable;
import java.util.List;

public abstract class AbstractJpaDao<K, T extends Serializable> implements IGenericDao<K, T> {
    protected EntityManager em;
    private Class<T> entityClass;

    public AbstractJpaDao() {
        this.em = EntityManagerHelper.getEntityManager();
    }

    //Pour connaitre qu'on travaille avec quelle classe
    public void setClass(Class<T> class2){
        this.entityClass= class2;
    }

    public T findOne(K id) {
        return em.find(entityClass, id);
    }

    public List<T> findAll() {
        return em.createQuery("select e from " + entityClass.getName() + " as e", entityClass).getResultList();
    }

    //CRUD
    public void create(T entity){
        EntityTransaction t = em.getTransaction();
        t.begin();
        em.persist(entity);
        t.commit();
    }

    public T findById(K id) {
        return em.find(entityClass, id);
    }

    public T update(T entity){
        EntityTransaction t = em.getTransaction();
        t.begin();
        T T_sync = em.merge(entity);
        t.commit();
        return T_sync;
    }

    public void delete(T entity){
        EntityTransaction t = em.getTransaction();
        t.begin();
        em.remove(entity);
        t.commit();
    }

    public void deleteById(K id) {
        T T_to_be_deleted = em.find(entityClass, id);
        em.remove(T_to_be_deleted);
    }
}

