peer-at-code-backend/src/be/jeffcheasey88/peeratcode/routes/PuzzleElement.java
jeffcheasey88 7858752406 Tries
2023-04-18 13:17:53 +02:00

52 lines
2 KiB
Java

package be.jeffcheasey88.peeratcode.routes;
import java.util.regex.Matcher;
import org.json.simple.JSONObject;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpUtil;
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.Completion;
import be.jeffcheasey88.peeratcode.model.Puzzle;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
public class PuzzleElement implements Response {
private final DatabaseRepository databaseRepo;
public PuzzleElement(DatabaseRepository databaseRepo) {
this.databaseRepo = databaseRepo;
}
@Route(path = "^\\/puzzle\\/([0-9]+)$", needLogin = true)
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
Puzzle puzzle = databaseRepo.getPuzzle(extractId(matcher));
if (puzzle != null) {
JSONObject puzzleJSON = new JSONObject();
puzzleJSON.put("id", puzzle.getId());
puzzleJSON.put("name", puzzle.getName());
puzzleJSON.put("content", puzzle.getContent());
puzzleJSON.put("scoreMax", puzzle.getScoreMax());
if(puzzle.getTags() != null) puzzleJSON.put("tags", puzzle.getJsonTags());
Completion completion = this.databaseRepo.getCompletionGroup(user.getId(), puzzle.getId());
if(completion != null && completion.getScore() >= 0){
puzzleJSON.put("score", completion.getScore());
puzzleJSON.put("tries", completion.getTries());
}
if(puzzle.getDepend() > 0) puzzleJSON.put("depend", puzzle.getDepend());
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *", "Content-Type: application/json");
writer.write(puzzleJSON.toJSONString());
}
else {
HttpUtil.responseHeaders(writer, 400, "Access-Control-Allow-Origin: *");
}
}
private int extractId(Matcher matcher) {
return Integer.parseInt(matcher.group(1));
}
}