package dev.peerat.backend.routes;

import java.time.LocalDateTime;
import java.util.regex.Matcher;

import org.json.simple.JSONObject;

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

	private final DatabaseRepository databaseRepo;

	public PuzzleElement(DatabaseRepository databaseRepo) {
		this.databaseRepo = databaseRepo;
	}
	
	@RouteDoc(path = "/puzzle/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du puzzle")
	@RouteDoc(responseCode = 400, responseDescription = "puzzle introuvable dans la base de donnée")
	@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de voir le puzzle en dehors de l'event")

	@Route(path = "^\\/puzzle\\/([0-9]+)$", needLogin = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		Puzzle puzzle = databaseRepo.getPuzzle(extractId(matcher));
		if (puzzle != null){
			Chapter chapter = this.databaseRepo.getChapter(puzzle);
			if(chapter.getStartDate() != null){
				if(LocalDateTime.now().isBefore(chapter.getStartDate().toLocalDateTime())){
					context.response(423);
					return;
				}
			}
//			if(chapter.getEndDate() != null){
//				if(LocalDateTime.now().isAfter(chapter.getEndDate().toLocalDateTime())){
//					writer.response(423, "Access-Control-Allow-Origin: *");
//					return;
//				}
//			}
			
			PeerAtUser user = context.getUser();
			
			JSONObject puzzleJSON = new JSONObject();
			puzzleJSON.put("id", puzzle.getId());
			puzzleJSON.put("name", puzzle.getName());
			puzzleJSON.put("content", puzzle.getContent());
			puzzleJSON.put("scoreMax", puzzle.getScoreMax());
			if(puzzle.getTags() != null) puzzleJSON.put("tags", puzzle.getJsonTags());
			Completion completion = this.databaseRepo.getCompletionGroup(user.getId(), puzzle.getId());
			if(completion != null && completion.getScore() >= 0){
				puzzleJSON.put("score", completion.getScore());
				puzzleJSON.put("tries", completion.getTries());
			}
			if(puzzle.getDepend() > 0) puzzleJSON.put("depend", puzzle.getDepend());
			context.response(200, "Content-Type: application/json");
			writer.write(puzzleJSON.toJSONString());
		}
		else {
			context.response(400);
		}
	}

	private int extractId(Matcher matcher) {
		return Integer.parseInt(matcher.group(1));
	}
}
