package eu.eudat.data.dao.databaselayer.context;

import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.jpa.hibernatequeryablelist.QueryableHibernateList;
import eu.eudat.queryable.queryableentity.DataEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;


@Repository("databaseCtx")
public class DatabaseContext<T extends DataEntity> {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    public DatabaseContext(EntityManagerFactory entityManagerFactory) {
        this.entityManager = entityManagerFactory.createEntityManager();
    }

    public QueryableList<T> getQueryable(Class<T> type) {
        return new QueryableHibernateList<>(this.entityManager, type).setEntity(type);
    }

    @Transactional
    public T createOrUpdate(T item, Class<T> type) {
        EntityManager entityManager = this.entityManager;
        if (item.getKeys() != null) {
            T oldItem = entityManager.find(type, item.getKeys());
            if (oldItem != null) {
                oldItem.update(item);
                entityManager.merge(oldItem);
                return oldItem;
            } else {
                entityManager.persist(item);
            }
        } else entityManager.persist(item);
        return item;
    }

    public void delete(T item) {
        this.entityManager.remove(item);
    }
}
