package controller.implementation;

import java.math.BigInteger;

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

import controller.PedidoController;
import domain.Pedido;

public class PedidoControllerImpl implements PedidoController {
	
	private static PedidoControllerImpl instance;
    protected EntityManager entityManager;
    
    public static PedidoController getInstance(){
    	if (instance == null)
    		instance = new PedidoControllerImpl();
        return instance;
    }
    
    private PedidoControllerImpl() {
        entityManager = getEntityManager();
    }
    
    private EntityManager getEntityManager() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("crudHibernate");
        if (entityManager == null || !entityManager.isOpen()) 
                 entityManager = factory.createEntityManager();
        return entityManager;
    }

	@Override
	public Pedido cadastrar(Pedido pedido) {
		try {
            entityManager.getTransaction().begin();
            entityManager.persist(pedido);
            entityManager.getTransaction().commit();
		} catch (Exception ex) {
            ex.printStackTrace();
            entityManager.getTransaction().rollback();
		}
		return pedido;
	}

	@Override
	public Pedido buscar(BigInteger id) {
		return entityManager.find(Pedido.class, id);
	}

	@Override
	public Pedido alterar(Pedido pedido) {
		try {
            entityManager.getTransaction().begin();
            entityManager.merge(pedido);
            entityManager.getTransaction().commit();
		} catch (Exception ex) {
            ex.printStackTrace();
            entityManager.getTransaction().rollback();
		}
		return pedido;
	}

	@Override
	public Boolean excluir(BigInteger id) {
		try {
            entityManager.getTransaction().begin();
            entityManager.remove(buscar(id));
            entityManager.getTransaction().commit();
		} catch (Exception ex) {
            ex.printStackTrace();
            entityManager.getTransaction().rollback();
            return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}
}
