package jp.bne.deno.ordermaid.dao;

import java.util.List;

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

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

import org.apache.log4j.Logger;
import com.google.inject.Inject;

public class SystemTable {
	@Inject
	EntityManager em;

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

	public SystemItem getSystemItem(String key, String defaultValue) {
		SystemItem ret = em.find(SystemItem.class, key);
		if (ret == null) {
			return new SystemItem(key, defaultValue);
		} else {
			return ret;
		}
	}

	@SuppressWarnings("unchecked")
	public List<SystemItem> findAll() {
		String jpql = "FROM SystemItem";
		Query query = em.createQuery(jpql);
		return query.getResultList();
	}

	public SystemItem save(SystemItem item) {
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		try {
			em.persist(item);
			em.flush();
			transaction.commit();
		} catch (Throwable e) {
			logger.error(e);
			transaction.rollback();
			throw new RuntimeException(e);
		}
		return item;
	}

	public void remove(SystemItem item) {
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		try {
			em.remove(item);
			em.flush();
			transaction.commit();
		} catch (Throwable e) {
			logger.error(e);
			transaction.rollback();
			throw new RuntimeException(e);
		}
	}

}
