package be.jeffcheasey88.peeratcode.routes;

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.model.Puzzle;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

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

}
