package es.uv.saic.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import es.uv.saic.domain.Usuari;
import es.uv.saic.feign.StatsClient;

// Controller to handle admin statistics page
@Controller
public class StatsController {
	
	@Autowired
    private SessionRegistry sessionRegistry;
	
	@Autowired
    private StatsClient sc;

	public static class ActiveSession {
		private String id;
		private String username;
		private String fullName;
		private String npi;
		private String lastRequest;
		private boolean expired;
		public void setId(String id) {this.id = id;}
		public void setUsername(String username) {this.username = username;}
		public void setFullName(String fullName) {this.fullName = fullName;}
		public void setNpi(String npi) {this.npi = npi;}
		public void setExpired(boolean expired) {this.expired = expired;}
		public void setLastRequest(String lastRequest) {this.lastRequest = lastRequest;}
		public String getId() {return this.id;}
		public String getUsername() {return this.username;}
		public String getFullName() {return this.fullName;}
		public String getNpi() {return this.npi;}
		public boolean getExpired() {return this.expired;}
		public String getLastRequest() {return this.lastRequest;}
	}
	
	public static class PendingEmail{
		private String username;
		private String fullName;
		private String email;
		public void setUsername(String username) {this.username = username;}
		public void setFullName(String fullName) {this.fullName = fullName;}
		public void setEmail(String email) {this.email = email;}
		public String getUsername() {return this.username;}
		public String getFullName() {return this.fullName;}
		public String getEmail() {return this.email;}
		
	}
	
	/*
	 * Renders the admin stats page
	 * 
	 * @param model The model to pass data to the view
	 * @param auth The authentication object
	 * @return The name of the view to render
	 *
	@GetMapping("/admin/stats")
	@Secured({"ROLE_ADMIN"})
	public String getStats(Model model, Authentication auth) {
		HashMap<String, Object> response =
                sc.getStats();

        if (response == null) {
			return "401";	
        }

		model.addAllAttributes(response);
		return "adminStats";
	}*/
	
	@GetMapping("/admin/stats")
	@Secured({"ROLE_ADMIN"})
	public String getStats(Model model, Authentication auth) {
		final List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
		List<ActiveSession> allLoggedUsers = new ArrayList<ActiveSession>();
		int totalActiveSessions = 0;
		int totalExpiredSessions = 0;
		
		for(Object principal : allPrincipals) {
			final List<SessionInformation> allSessions = sessionRegistry.getAllSessions(principal, true);
			for(final SessionInformation session : allSessions) {
				final ActiveSession s = new ActiveSession();
				if(session.isExpired()) {
					totalExpiredSessions++;
				}
				else {
					totalActiveSessions++;
				}
				Usuari x = ((Usuari)principal);
				s.setId(Integer.toString(session.hashCode()));
				s.setExpired(session.isExpired());
				SimpleDateFormat sdt = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss");
				s.setLastRequest(sdt.format(session.getLastRequest()));
				s.setUsername(x.getUsuari());
				s.setFullName(x.getNom() + " " + x.getCognoms());
				s.setNpi("");
				allLoggedUsers.add(s);
			}
		}
		
		model.addAttribute("activeSessions", allLoggedUsers);
		model.addAttribute("totalActiveSessions", totalActiveSessions);
		model.addAttribute("totalExpiredSessions", totalExpiredSessions);
		model.addAttribute("pendingEmails", sc.getPendingEmails());
		return "adminStats";
	}
}
