package dev.peerat.backend.routes.users;

import static dev.peerat.framework.RequestType.POST;

import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;

import org.json.simple.JSONObject;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.repository.DatabaseRepository;
import dev.peerat.backend.utils.FormResponse;
import dev.peerat.framework.Context;
import dev.peerat.framework.HttpReader;
import dev.peerat.framework.HttpWriter;
import dev.peerat.framework.Route;

public class Register extends FormResponse {

	private DatabaseRepository databaseRepo;
	private Map<String, Integer> playersWaiting;

	public Register(DatabaseRepository databaseRepo, Map<String, Integer> playersWaiting){
		this.databaseRepo = databaseRepo;
		this.playersWaiting = playersWaiting;
	}
	
	@RouteDoc(path = "/register", responseCode = 200, responseDescription = "L'utilisateur est inscrit")
	@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est connecté")
	@RouteDoc(responseCode = 400, responseDescription = "Aucune données fournie / données invalide")

	@Route(path = "^\\/register$", type = POST)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		if (context.isLogged()){
			context.response(403);
			return;
		}
		JSONObject json = json(reader);
		if(!areValids("email")){
			context.response(400);
			return;
		}
		
		String email = (String) json.get("email");

		boolean emailAvailable = databaseRepo.checkEmailAvailability(email);
		if(emailAvailable){
			playersWaiting.put(email, codeGenerator());
			context.response(200);
		}else{
			context.response(400);
			JSONObject error = new JSONObject();
			error.put("email_valid", emailAvailable);
			writer.write(error.toJSONString());
		}
	}
	
	private int codeGenerator(){
		int min = 1000;
		int max = 9999;
		return new Random().nextInt((max-min)) + min;

	}
	
}
