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 dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.repository.DatabaseRepository;
import dev.peerat.backend.utils.FormResponse;
import dev.peerat.backend.utils.Mail;
import dev.peerat.framework.Context;
import dev.peerat.framework.HttpReader;
import dev.peerat.framework.HttpWriter;
import dev.peerat.framework.Route;
import dev.peerat.framework.utils.json.JsonMap;

public class Register extends FormResponse {

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

	public Register(DatabaseRepository databaseRepo, Map<String, Integer> playersWaiting, Mail mail){
		this.databaseRepo = databaseRepo;
		this.playersWaiting = playersWaiting;
		this.mail = mail;
	}
	
	@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;
		}
		JsonMap json = json(reader);
		if(!areValids("email")){
			context.response(400);
			return;
		}
		
		String email = json.get("email");

		boolean emailAvailable = databaseRepo.checkEmailAvailability(email);
		if(emailAvailable){
			int code = codeGenerator();
			playersWaiting.put(email, code);
			mail.send(email, "Welcome @ Peer @ Code", "Your check code is "+code+" !");
			context.response(200);
		}else{
			context.response(400);
			JsonMap error = new JsonMap();
			error.set("email_valid", emailAvailable);
			writer.write(error.toString());
		}
	}
	
	private int codeGenerator(){
		int min = 1000;
		int max = 9999;
		return new Random().nextInt((max-min)) + min;

	}
	
}
