package org.academiadecodigo.enuminatti.hibernatebootstrap.services;

import org.academiadecodigo.enuminatti.hibernatebootstrap.models.User;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.RollbackException;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class UserService {

    EntityManagerFactory emf;

    public UserService() {
        this.emf = Persistence.createEntityManagerFactory("test");
    }

    public User edit(User user) {
        EntityManager em = emf.createEntityManager();

        try {
            em.getTransaction().begin();

            User savedUser = em.merge(user);

            em.getTransaction().commit();

            return savedUser;
        } catch (RollbackException e) {
            em.getTransaction().rollback();
            return null;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public User save(User user) {
        EntityManager em = emf.createEntityManager();

        try {
            em.getTransaction().begin();

            em.persist(user);

            em.getTransaction().commit();

            return user;
        } catch (RollbackException e) {
            em.getTransaction().rollback();
            return null;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public User get(Integer id) {
        EntityManager em = emf.createEntityManager();

        try {
            return em.find(User.class, id);
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void close() {
        emf.close();
    }
}
