package dev.peerat.backend.routes;

import java.util.List;
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.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 ChapterList implements Response {

	private final DatabaseRepository databaseRepo;

	public ChapterList(DatabaseRepository databaseRepo) {
		this.databaseRepo = databaseRepo;
	}
	
	@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) {
				JSONObject chapterJSON = new JSONObject();
				chapterJSON.put("id", chapter.getId());
				chapterJSON.put("name", chapter.getName());
				chapterJSON.put("show", chapter.isInCurrentTime());
				chaptersJSON.add(chapterJSON);
			}
			context.response(200);
			writer.write(chaptersJSON.toJSONString());
		} else {
			context.response(400);
		}
	}

}
