package dev.peerat.backend.routes;

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

import org.json.simple.JSONObject;

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;

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());
		}
		JSONObject playerJSON = new JSONObject();
		if (player != null) {
			playerJSON.put("pseudo", player.getPseudo());
			playerJSON.put("email", player.getEmail());
			playerJSON.put("firstname", player.getFirstname());
			playerJSON.put("lastname", player.getLastname());
			playerJSON.put("description", player.getDescription());
			if (player.getGroups() != null)
				playerJSON.put("groups", player.getJsonGroups());
			playerJSON.put("rank", player.getRank());
			playerJSON.put("score", player.getTotalScore());
			playerJSON.put("completions", player.getTotalCompletion());
			playerJSON.put("completionsList", player.getJsonCompletions());
			playerJSON.put("tries", player.getTotalTries());
			if (player.getBadges() != null)
				playerJSON.put("badges", player.getJsonBadges());
			if (player.getAvatar() != null)
				playerJSON.put("avatar", Base64.getEncoder().encodeToString(player.getAvatar()));
			context.response(200);
			writer.write(playerJSON.toJSONString().replace("\\", ""));
		} else {
			context.response(400);
		}
	}

}
