package info.bukova.isspst.security;

import info.bukova.isspst.SessionData;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.User;
import info.bukova.isspst.data.UserSettingsData;
import info.bukova.isspst.data.Workgroup;
import info.bukova.isspst.services.users.UserService;
import info.bukova.isspst.services.workgroups.WorkgroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	
	@Autowired
	private SessionData sessionData;
	@Autowired
	private WorkgroupService workgroupService;
	@Autowired
	private UserService userService;
	
	private static final Logger logger = LoggerFactory.getLogger(LoginSuccessHandler.class);

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication auth) throws IOException,
			ServletException {
		
		User u = (User) userService.loadUserByUsername(((User)auth.getPrincipal()).getUsername());
		
		logger.info("User " + u.getUsername() + " logged in");
		
		sessionData.setUserCentres(workgroupService.getUserCentres((User) auth.getPrincipal()));
		sessionData.setUserOnlyCentres(workgroupService.getUserCentres((User) auth.getPrincipal(), true));
		sessionData.setUserWorkgroups(workgroupService.getUserWorkgroups((User) auth.getPrincipal()));
		workgroupService.loadParents(u);
		sessionData.setCurrentUser(u);
		
		Map<Integer, List<Role>> wgRoles = new HashMap<Integer, List<Role>>();
		for (Workgroup w : u.getParents()) {
			wgRoles.put(w.getId(), workgroupService.getUserWorkgroupRoles(w, u));
		}
		sessionData.setWorkgroupRoles(wgRoles);
		
		UserSettingsData userSettings = userService.getUserSettings();
		if (userSettings == null) {
			userSettings = new UserSettingsData();
			userService.setUserSettings(userSettings);
			userService.update(u);
		}
		
		super.onAuthenticationSuccess(request, response, auth);
	}

}
