package jp.bne.deno.ordermaid.dao;

import java.util.List;

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

import org.apache.log4j.Logger;

import jp.bne.deno.ordermaid.model.MenuItem;

import com.google.inject.Inject;

public class MenuItemTable {
	@Inject
	EntityManager em;
	Logger logger = Logger.getLogger(MenuItemTable.class);

	private MenuItem find(int menuId) {
		return em.find(MenuItem.class, menuId);
	}

	@SuppressWarnings("unchecked")
	public List<MenuItem> findByTypeId(int menuTypeId) {
		String jpql = "FROM  MenuItem m WHERE MENUTYPEID = ? ORDER BY sort";
		Query query = em.createQuery(jpql);
		query.setParameter(1, menuTypeId);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<MenuItem> findAll() {
		String jpql = "FROM  MenuItem m ORDER BY sort";
		return em.createQuery(jpql).getResultList();
	}

	public MenuItem save(MenuItem menuItem) {
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		try {
			em.merge(menuItem);
			em.flush();
			transaction.commit();
		} catch (Throwable e) {
			logger.error(e);
			transaction.rollback();
		}
		return menuItem;
	}

	public void remove(int menuId) {
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		try {
			em.remove(find(menuId));
			em.flush();
			transaction.commit();
		} catch (Throwable e) {
			logger.error(e);
			transaction.rollback();
		}
	}
}
