package be.jeffcheasey88.peeratcode.routes;

import java.util.regex.Matcher;

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.repository.DatabaseRepository;

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, User user, HttpReader reader, HttpWriter writer) throws Exception {
		int puzzle = Integer.parseInt(matcher.group(1));

		int score = this.repo.getScore(user.getId(), puzzle);
		if (score < 0) {
			writer.response(425, "Access-Control-Allow-Origin: *");
		} else {
			writer.response(200, "Access-Control-Allow-Origin: *");
			writer.write(score + "");
		}
	}

}
