package de.jottyfan.camporganizer.module.camplist;

import javax.servlet.http.HttpServletRequest;

import org.keycloak.KeycloakSecurityContext;
import org.springframework.ui.Model;

/**
 *
 * @author jotty
 *
 */
public abstract class CommonController {

	/**
	 * try to get current keycloak user
	 *
	 * @param request the request
	 * @return the preferred username or null
	 */
	public String getCurrentUser(HttpServletRequest request) {
		KeycloakSecurityContext ksc = (KeycloakSecurityContext) request
				.getAttribute(KeycloakSecurityContext.class.getName());
		return ksc == null ? null : ksc.getIdToken().getPreferredUsername();
	}

	/**
	 * try to get th currnt keycloak email
	 *
	 * @param request the request
	 * @return the email or null
	 */
	public String getCurrentEmail(HttpServletRequest request) {
		KeycloakSecurityContext ksc = (KeycloakSecurityContext) request
				.getAttribute(KeycloakSecurityContext.class.getName());
		return ksc == null ? null : ksc.getIdToken().getEmail();
	}

	/**
	 * setup the session for the template
	 *
	 * @param model   the model
	 * @param request the request
	 */
	public void setupSession(Model model, HttpServletRequest request) {
		String username = getCurrentUser(request);
		model.addAttribute("currentUser", username);
	}

	/**
	 * return true if the user has a valid keycloak session token
	 *
	 * @param request the request
	 * @return true or false
	 */
	public boolean isLoggedIn(HttpServletRequest request) {
		return getCurrentUser(request) != null;
	}
}
