package org.ros.chatto.controller;

import java.security.Principal;
import java.util.Optional;

import org.ros.chatto.dto.ChatMessageDTO;
import org.ros.chatto.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequiredArgsConstructor
@Slf4j
public class Home {

	@Autowired
	private final UserService userService;

	@RequestMapping("/")
	public String showPage(Model model, Principal principal) {
		final String welcomeMessage = Optional.ofNullable(principal).map(p -> {
			return String.format("Welcome back %s!", p.getName());
		}).orElse("Welcome to chatto");
		model.addAttribute("message", welcomeMessage);
		return "home";
	}

	@GetMapping("/chat")
	public String showChat(Model model, Principal principal) {
		model.addAttribute(new ChatMessageDTO());

		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();

		boolean isAdmin = authentication.getAuthorities().stream()
				.anyMatch(r -> r.getAuthority().equals("ROLE_ADMIN")
						|| r.getAuthority().equals("ROLE_SUPER_USER"));
		log.trace("Is admin? " + isAdmin);
		// model.addAttribute("activeUsers",
		// 		userService.getOtherActiveUsers(principal.getName()));
		return "chat";
	}
}
