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.Badge;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

public class BadgeDetails implements Response {

	private final DatabaseRepository databaseRepo;

	public BadgeDetails(DatabaseRepository databaseRepo) {
		this.databaseRepo = databaseRepo;
	}
	
	@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, User user, HttpReader reader, HttpWriter writer) throws Exception {
		if (matcher.groupCount() > 0) {
			int badgeId = Integer.parseInt(matcher.group(1));
			Badge badge = databaseRepo.getBadge(badgeId);
			JSONObject badgeJSON = new JSONObject();
			if (badge != null) {
				badgeJSON.put("name", badge.getName());
				if (badge.getLogo() != null)
					badgeJSON.put("logo", Base64.getEncoder().encodeToString(badge.getLogo()));
				badgeJSON.put("level", badge.getLevel());
			}
			writer.response(200, "Access-Control-Allow-Origin: *");
			writer.write(badgeJSON.toJSONString().replace("\\", ""));
		} else {
			writer.response(400, "Access-Control-Allow-Origin: *");
		}
	}

}