package com.wishurgift.persistence.repository;

import com.wishurgift.persistence.entity.Persistable;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Optional;

@Slf4j
public abstract class PersistableRepository<E extends Persistable> implements Repository<E> {

    @PersistenceContext(unitName = "wishurgiftPU")
    protected EntityManager entityManager;

    @Override
    public void insert(E entity) {
        if (entity == null) {
            return;
        }
        entityManager.persist(entity);
        entityManager.flush();
        log.info("Insert {} entity", getEntityClass());
    }

    @Override
    public void update(E entity) {
        update(entity, false);
    }

    @Override
    public void update(E entity, boolean flush) {
        if (entity == null) {
            return;
        }
        entityManager.merge(entity);
        if (flush) {
            entityManager.flush();
        }
        log.info("Update {} entity, id={} flush={}", getEntityClass(), entity.getId(), flush);
    }

    @Override
    public void delete(E entity) {
        if (entity == null) {
            return;
        }
        entityManager.remove(entity);
        log.info("Delete {} entity, id={}", getEntityClass(), entity.getId());
    }

    @Override
    public E getById(long id) {
        log.info("Select {} entity, id={}", getEntityClass(), id);
        return entityManager.find(getEntityClass(), id);
    }

    @Override
    public Optional<E> findById(long id) {
        E entity = getById(id);
        if (entity == null) {
            return Optional.empty();
        }
        return Optional.of(entity);
    }

    protected abstract Class<E> getEntityClass();

}
