package dev.peerat.backend.routes;

import java.util.List;
import java.util.regex.Matcher;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.Chapter;
import dev.peerat.backend.repository.DatabaseChapterRepository;
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 ChapterList implements Response {

	private final DatabaseChapterRepository databaseRepo;

	public ChapterList(DatabaseRepository databaseRepo) {
		this.databaseRepo = databaseRepo.getChapterRepository();
	}
	
	@RouteDoc(path = "/chapters", responseCode = 200, responseDescription = "JSON contenant les informations des chapitres")
	@RouteDoc(responseCode = 400, responseDescription = "Aucun chapitre trouver")

	@Route(path = "^\\/chapters$", needLogin = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		List<Chapter> allChapters = databaseRepo.getAllChapters();
		if (allChapters != null) {
			JsonArray chaptersJSON = new JsonArray();
			for (Chapter chapter : allChapters) {
				JsonMap chapterJSON = new JsonMap();
				chapterJSON.set("id", chapter.getId());
				chapterJSON.set("name", chapter.getName());
				chapterJSON.set("show", chapter.hasStarted());
				if(chapter.getStartDate() != null) chapterJSON.set("start", chapter.getStartDate().toString());
				if(chapter.getEndDate() != null) chapterJSON.set("end", chapter.getEndDate().toString());
				chaptersJSON.add(chapterJSON);
			}
			context.response(200);
			writer.write(chaptersJSON.toString());
		} else {
			context.response(400);
		}
	}

}
