package org.se.lab.data;

import org.apache.log4j.Logger;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.sql.SQLException;
import java.util.List;

class UserDAOImpl
	implements UserDAO
{
	private final Logger LOG = Logger.getLogger(UserDAOImpl.class);
		
	@PersistenceContext
	private EntityManager em;

	
	/*
	 * CRUD Operations
	 */	
	
	@Override
	public User insert(User article)
	{
		LOG.info("insert(" + article + ")");
		em.persist(article);
		return article;
	}

	@Override
	public User update(User article)
	{
		LOG.info("update(" + article + ")");
		return em.merge(article);
	}

	@Override
	public void delete(User article)
	{
		LOG.info("delete(" + article + ")");
		em.remove(article);
	}

	@Override
	public User findById(int id)
	{
		LOG.info("findById(" + id + ")");

		//TODO remove when DB Connection ok
		try {
			org.hibernate.engine.spi.SessionImplementor sessionImp =
					(org.hibernate.engine.spi.SessionImplementor) em.getDelegate();
			String metadata = sessionImp.connection().getMetaData().getURL();
			LOG.info("URL: " + metadata);
		}
		catch (SQLException e)
		{
			throw new RuntimeException();
		}

		return em.find(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll()
	{
		LOG.info("findAll()");
		final String hql = "SELECT u FROM " + User.class.getName() + " AS u";	    
	    return em.createQuery(hql).getResultList();
	}	
	
	
	/*
	 * Factory methods
	 */

	@Override
	public User createUser(String username, String password)
	{
		LOG.info("createArticle(\"" + username + "\"," + "***" +")");
		
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);	
		insert(u);
		return u;
	}

	@Override
	public User loadByUsername(String username) {
		//TODO implement
		return null;
	}
}

@@ -147,39 +147,8 @@
 t;%0D%0A
-import java.sql.SQLException;%0D%0A
 impo
@@ -167,16 +167,16 @@
 .List;%0D%0A
+
 %0D%0Aclass 
@@ -278,20 +278,18 @@
 lass);%0D%0A
-%09%09
 %0D%0A
+
 %09@Persis
@@ -332,19 +332,18 @@
  em;%0D%0A%0D%0A
-%09
 %0D%0A
+
 %09/*%0D%0A%09 *
@@ -364,20 +364,18 @@
 ns%0D%0A%09 */
-%09
 %0D%0A
-%09
 %0D%0A%09@Over
@@ -793,32 +793,32 @@
 Id(int id)%0D%0A%09%7B%0D%0A
+
 %09%09LOG.info(%22find
@@ -842,370 +842,8 @@
 );%0D%0A
-%0D%0A%09%09//TODO remove when DB Connection ok%0D%0A%09%09try %7B%0D%0A%09%09%09org.hibernate.engine.spi.SessionImplementor sessionImp =%0D%0A%09%09%09%09%09(org.hibernate.engine.spi.SessionImplementor) em.getDelegate();%0D%0A%09%09%09String metadata = sessionImp.connection().getMetaData().getURL();%0D%0A%09%09%09LOG.info(%22URL: %22 + metadata);%0D%0A%09%09%7D%0D%0A%09%09catch (SQLException e)%0D%0A%09%09%7B%0D%0A%09%09%09throw new RuntimeException();%0D%0A%09%09%7D%0D%0A%0D%0A
 %09%09re

Rollback to Version before