package com.softgraf.vendas.model.repositorio;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.softgraf.vendas.model.entity.Pedido;
import com.softgraf.vendas.model.repositorio.abstrato.AbstractRepositorio;

public class RepositorioPedido implements AbstractRepositorio<Pedido>{

	private static final long serialVersionUID = -2794990205679853638L;
	private EntityManager em;

	public RepositorioPedido(EntityManager em) {
		this.em = em;
	}

	@Override
	public boolean adicionar(Pedido pedido) {
		EntityTransaction tx = em.getTransaction();
		try {
			
			tx.begin();
			em.persist(pedido);
			tx.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

	@Override
	public Pedido buscarPorId(Integer id) {
		return em.find(Pedido.class, id);
	}
	
	public Pedido buscarPorId(String id) {
		return buscarPorId(Integer.parseInt(id));
	}

	@Override
	public boolean atualizar(Pedido pedido) {
		EntityTransaction tx = em.getTransaction();
		try {
			
			tx.begin();
			em.merge(pedido);
			tx.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

	@Override
	public boolean remover(Pedido pedido) {
		EntityTransaction tx = em.getTransaction();
		
		try {
			
			tx.begin();
			em.remove(pedido);
			tx.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

	@Override
	public List<Pedido> listarTodos() {
		return em.createQuery("from Pedido", Pedido.class).getResultList();
	}

	@Override
	public List<Pedido> listarTodos(int maximo) {
		return em.createQuery("from Pedido", Pedido.class).setMaxResults(maximo).getResultList();
	}

}
