package de.jottyfan.camporganizer.module.camplist;

import java.security.Principal;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.ModelAttribute;

import de.jottyfan.camporganizer.module.registration.KeycloakRepository;

/**
 *
 * @author jotty
 *
 */
public abstract class CommonController {
	private static final Logger LOGGER = LogManager.getLogger();

	@Autowired
	private KeycloakRepository keycloak;

	/**
	 * try to get current keycloak user
	 *
	 * @param principal the principal
	 * @return the preferred username or null
	 */
	public String getCurrentUser(Principal principal) {
		return principal == null ? null : principal.getName();
	}

	/**
	 * try to get th currnt keycloak email
	 *
	 * @param principal the principal
	 * @return the email or null
	 */
	public String getCurrentEmail(Principal principal) {
		if (principal instanceof OAuth2AuthenticationToken) {
			OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) principal;
			if (token != null) {
				OAuth2User user = token.getPrincipal();
				if (user != null) {
					return user.getAttribute("email");
				}
			}
		} else {
			LOGGER.error("could not find email for {}", principal);
		}
		return null;
	}

	@ModelAttribute("currentUser")
	public String getCurrentUser() {
		SecurityContext context = SecurityContextHolder.getContext();
		if (context != null) {
			Authentication authentication = context.getAuthentication();
			if (authentication != null) {
				DefaultOidcUser dou = (DefaultOidcUser) authentication.getPrincipal();
				return dou == null ? null : dou.getName();
			}
		}
		return null;
	}

	@ModelAttribute("keycloakProfileUrl")
	public String getKeycloakProfileUrl() {
		return keycloak.getUserClientUrl();
	}

	@ModelAttribute("keycloakPasswordUrl")
	public String getKeycloakPasswordUrl() {
		return keycloak.getPasswordClientUrl();
	}

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