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.MenuSet;
import jp.bne.deno.ordermaid.model.MenuType;

import com.google.inject.Inject;

public class MenuSetTable {
	@Inject
	EntityManager em;

	Logger logger = Logger.getLogger(MenuSetTable.class);

	private MenuType find(int menuTypeId) {
		return em.find(MenuType.class, menuTypeId);
	}

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

	public MenuSet find(String menuSetName) {
		String jpql = "FROM  MenuSet s WHERE menuSetName = ?";
		Query query = em.createQuery(jpql);
		query.setParameter(1, menuSetName);
		return (MenuSet) query.getSingleResult();
	}

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

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