package be.jeffcheasey88.peeratcode.routes;

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

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

import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
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.Chapter;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

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, User user, 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());
				if (chapter.getStartDate() != null)
					chapterJSON.put("startDate", chapter.getStartDate().toString());
				if (chapter.getEndDate() != null)
					chapterJSON.put("endDate", chapter.getEndDate().toString());
				chaptersJSON.add(chapterJSON);
			}
			writer.response(200, "Access-Control-Allow-Origin: *");
			writer.write(chaptersJSON.toJSONString());
		} else {
			writer.response(400, "Access-Control-Allow-Origin: *");
		}
	}

}
