package dev.peerat.backend.routes;

import java.util.Base64;
import java.util.regex.Matcher;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.PeerAtUser;
import dev.peerat.backend.model.Player;
import dev.peerat.backend.repository.DatabaseRepository;
import dev.peerat.framework.Context;
import dev.peerat.framework.HttpReader;
import dev.peerat.framework.HttpWriter;
import dev.peerat.framework.Response;
import dev.peerat.framework.Route;
import dev.peerat.framework.utils.json.JsonMap;

public class PlayerDetails implements Response {

	private final DatabaseRepository databaseRepo;

	public PlayerDetails(DatabaseRepository databaseRepo) {
		this.databaseRepo = databaseRepo;
	}
	
	@RouteDoc(path = "/player/{id}", responseCode = 200, responseDescription = "JSON contenant les informations de l'utilisateur")
	@RouteDoc(responseCode = 400, responseDescription = "Utilisateur introuvable dans la base de donnée")

	@Route(path = "^\\/player\\/?(.+)?$", needLogin = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		Player player;
		if (matcher.group(1) != null) {
			player = databaseRepo.getPlayerDetails(matcher.group(1));
		} else {
			PeerAtUser user = context.getUser();
			player = databaseRepo.getPlayerDetails(user.getId());
		}
		JsonMap playerJSON = new JsonMap();
		if (player != null) {
			playerJSON.set("pseudo", player.getPseudo());
			playerJSON.set("email", player.getEmail());
			playerJSON.set("firstname", player.getFirstname());
			playerJSON.set("lastname", player.getLastname());
			playerJSON.set("description", player.getDescription());
			if (player.getGroups() != null)
				playerJSON.set("groups", player.getJsonGroups());
			playerJSON.set("rank", player.getRank());
			playerJSON.set("score", player.getTotalScore());
			playerJSON.set("completions", player.getTotalCompletion());
			playerJSON.set("completionsList", player.getJsonCompletions());
			playerJSON.set("tries", player.getTotalTries());
			if (player.getBadges() != null)
				playerJSON.set("badges", player.getJsonBadges());
			if (player.getAvatar() != null)
				playerJSON.set("avatar", Base64.getEncoder().encodeToString(player.getAvatar()));
			context.response(200);
			writer.write(playerJSON.toString().replace("\\", ""));
		} else {
			context.response(400);
		}
	}

}
