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.Badge;
import dev.peerat.backend.repository.DatabaseBadgeRepository;
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 BadgeDetails implements Response {

	private final DatabaseBadgeRepository databaseRepo;

	public BadgeDetails(DatabaseRepository databaseRepo) {
		this.databaseRepo = databaseRepo.getBadgeRepository();
	}
	
	@RouteDoc(path = "/badge/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du badge")
	@RouteDoc(responseCode = 400, responseDescription = "Aucun id donner")

	@Route(path = "^\\/badge\\/([0-9]+)$", needLogin = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		if (matcher.groupCount() > 0) {
			int badgeId = Integer.parseInt(matcher.group(1));
			Badge badge = databaseRepo.getBadge(badgeId);
			JsonMap badgeJSON = new JsonMap();
			if(badge != null){
				badgeJSON.set("name", badge.getName());
				if(badge.getLogo() != null) badgeJSON.set("logo", Base64.getEncoder().encodeToString(badge.getLogo()));
				badgeJSON.set("level", badge.getLevel());
			}
			context.response(200);
			writer.write(badgeJSON.toString().replace("\\", ""));
		} else {
			context.response(400);
		}
	}

}