package com.github.aureliano.verbum_domini.web.listener;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

import com.github.aureliano.verbum_domini.core.bean.UserBean;
import com.github.aureliano.verbum_domini.core.dao.UserDao;
import com.github.aureliano.verbum_domini.core.helper.HashHelper;
import com.github.aureliano.verbum_domini.core.impl.bean.UserBeanImpl;
import com.github.aureliano.verbum_domini.core.impl.dao.UserDaoImpl;

public class PrepareUserServletContextListener implements ServletContextListener {

	private static final Logger logger = Logger.getLogger(PrepareUserServletContextListener.class);
	
	private UserDao userDao;
	
	public PrepareUserServletContextListener() {
		this.userDao = new UserDaoImpl();
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		logger.info(" >>> Prepare default users.");
		this.saveUser("santo_antonio", System.getenv("DEFAULT_USER_PASSWORD"));
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) { }
	
	private void saveUser(String login, String password) {
		UserBean user = this.findUserWithLogin(login);
		
		if (user == null) {
			user = this.createUser(login);
		}
		
		user.setPassword(password);
		user.setPassword(HashHelper.generatePasswordHash(user));
		
		this.userDao.save(user);
		logger.info("User " + login + " was saved.");
	}
	
	private UserBean createUser(String login) {
		UserBean user = new UserBeanImpl();
		
		user.setActive(true);
		user.setCreation(new Date());
		user.setLogin(login);
		user.setSaltNumber(HashHelper.generateSaltNumber());
		
		return user;
	}
	
	private UserBean findUserWithLogin(String login) {
		UserBean filter = new UserBeanImpl();
		filter.setLogin(login);
		
		List<UserBean> elements = this.userDao.list(filter).getElements();
		return ((elements.isEmpty()) ? null : elements.get(0));
	}
}
@@ -182,24 +182,68 @@
 tListener;%0A%0A
+import org.apache.commons.lang.StringUtils;%0A
 import org.a
@@ -258,24 +258,24 @@
 g4j.Logger;%0A
-
 %0Aimport com.
@@ -773,16 +773,98 @@
 class);%0A
+%09private static final String DEFAULT_USER_PASSWORD_KEY = %22DEFAULT_USER_PASSWORD%22;%0A
 %09%0A%09priva
@@ -1095,77 +1095,293 @@
 ;%0A%09%09
-this.saveUser(%22santo_antonio%22, System.getenv(%22DEFAULT_USER_PASSWORD%22)
+String password = System.getenv(DEFAULT_USER_PASSWORD_KEY);%0A%09%09%0A%09%09if (StringUtils.isEmpty(password)) %7B%0A%09%09%09logger.warn(%22 Ignoring user saving because no password was found as environment variable %22 + DEFAULT_USER_PASSWORD_KEY);%0A%09%09%09return;%0A%09%09%7D%0A%09%09%0A%09%09this.saveUser(%22santo_antonio%22, password
 );%0A%09

Save default user.