package dev.peerat.backend.routes;

import java.util.regex.Matcher;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.Chapter;
import dev.peerat.backend.model.PeerAtUser;
import dev.peerat.backend.model.Puzzle;
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.JsonArray;
import dev.peerat.framework.utils.json.JsonMap;

public class ChapterElement implements Response {

	private final DatabaseRepository databaseRepo;

	public ChapterElement(DatabaseRepository databaseRepo) {
		this.databaseRepo = databaseRepo;
	}

	@RouteDoc(path = "/chapter/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du chapitre demander")
	@RouteDoc(responseCode = 400, responseDescription = "Aucun id donner")
	
	@Route(path = "^\\/chapter\\/([0-9]+)$", needLogin = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		Chapter chapter = databaseRepo.getChapter(Integer.parseInt(matcher.group(1)));
		if (chapter != null){
			JsonMap chapterJSON = new JsonMap();
			chapterJSON.set("id", chapter.getId());
			chapterJSON.set("name", chapter.getName());
			boolean show = chapter.hasStarted();
			chapterJSON.set("show", show);
			PeerAtUser user = context.getUser();
			if(show){
				JsonArray puzzles = new JsonArray();
				for (Puzzle puzzle : chapter.getPuzzles()){
					JsonMap puzzleJSON = new JsonMap();
					puzzleJSON.set("id", puzzle.getId());
					puzzleJSON.set("name", puzzle.getName());
					puzzleJSON.set("scoreMax", puzzle.getScoreMax());
					if (puzzle.getTags() != null) puzzleJSON.set("tags", puzzle.getJsonTags());
					int score = this.databaseRepo.getScore(user.getId(), puzzle.getId());
					if(score >= 0) puzzleJSON.set("score", score);
					puzzleJSON.set("show", puzzle.hasStarted());
					puzzles.add(puzzleJSON);
				}
				chapterJSON.set("puzzles", puzzles);
			}
			context.response(200);
			writer.write(chapterJSON.toString());
		} else {
			context.response(400);
		}
	}

}
