package dev.peerat.backend.routes;

import java.util.regex.Matcher;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.PeerAtUser;
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 Result implements Response {

	private DatabaseRepository repo;

	public Result(DatabaseRepository repo) {
		this.repo = repo;
	}
	
	@RouteDoc(path = "/result/<id>", responseCode = 200, responseDescription = "Le score")
	@RouteDoc(responseCode = 425, responseDescription = "Puzzle pas compléter")

	@Route(path = "^\\/result\\/(\\d+)$", needLogin = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		int puzzle = Integer.parseInt(matcher.group(1));
		
		PeerAtUser user = context.getUser();
		
		int score = this.repo.getScore(user.getId(), puzzle);
		if (score < 0) {
			context.response(425);
		} else {
			context.response(200);
			writer.write(score + "");
		}
	}

}
