package be.jeffcheasey88.peeratcode.routes;

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

import org.json.simple.JSONObject;

import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
import be.jeffcheasey88.peeratcode.framework.Response;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Player;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

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, User user, HttpReader reader, HttpWriter writer) throws Exception {
		Player player;
		if (matcher.group(1) != null) {
			player = databaseRepo.getPlayerDetails(matcher.group(1));
		} else {
			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()));
			writer.response(200, "Access-Control-Allow-Origin: *");
			writer.write(playerJSON.toJSONString().replace("\\", ""));
		} else {
			writer.response(400, "Access-Control-Allow-Origin: *");
		}
	}

}
