package dev.peerat.backend.routes;

import java.util.regex.Matcher;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

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;

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){
			JSONObject chapterJSON = new JSONObject();
			chapterJSON.put("id", chapter.getId());
			chapterJSON.put("name", chapter.getName());
			boolean show = chapter.isInCurrentTime();
			chapterJSON.put("show", show);
			PeerAtUser user = context.getUser();
			if(show){
				JSONArray puzzles = new JSONArray();
				for (Puzzle puzzle : chapter.getPuzzles()){
					JSONObject puzzleJSON = new JSONObject();
					puzzleJSON.put("id", puzzle.getId());
					puzzleJSON.put("name", puzzle.getName());
					puzzleJSON.put("scoreMax", puzzle.getScoreMax());
					if (puzzle.getTags() != null) puzzleJSON.put("tags", puzzle.getJsonTags());
					int score = this.databaseRepo.getScore(user.getId(), puzzle.getId());
					if(score >= 0) puzzleJSON.put("score", score);
					puzzles.add(puzzleJSON);
				}
				chapterJSON.put("puzzles", puzzles);
			}
			context.response(200);
			writer.write(chapterJSON.toJSONString());
		} else {
			context.response(400);
		}
	}

}
