package dev.peerat.backend.routes.users;

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

import java.lang.reflect.Constructor;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;

import dev.peerat.backend.Configuration;
import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.repository.DatabaseAuthRepository;
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.Injection;
import dev.peerat.framework.Route;
import dev.peerat.framework.utils.json.JsonMap;

public class Register extends FormResponse{

	private DatabaseAuthRepository databaseRepo;
	private Map<String, String> playersWaiting;
	private Mail mail;
	private String host;
	private List<Random> randoms;

	public Register(DatabaseRepository databaseRepo, @Injection("waitting") Map<String, String> playersWaiting, Mail mail, Configuration config){
		this.databaseRepo = databaseRepo.getAuthRepository();
		this.playersWaiting = playersWaiting;
		this.mail = mail;
		this.host = config.getTokenIssuer();
		this.randoms = new ArrayList<>();
		
		Random random = new Random();
		int randoms = random.nextInt(10)+3;
		for(int i = 0; i < randoms; i++) this.randoms.add(new SecureRandom());
		
		try {
			Constructor<?> constructor = UUID.class.getDeclaredConstructor(byte[].class);
			constructor.setAccessible(true);
			this.uuidBuilder = constructor;
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	@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){
			String 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 Constructor<?> uuidBuilder;
	private int[] start = {4, 9, 14, 19};
	
	private String codeGenerator() throws Exception{
		Random random = new Random();
		Random target = this.randoms.get(random.nextInt(this.randoms.size()));
		byte[] arrayOfByte = new byte[16];
		target.nextBytes(arrayOfByte);
	    arrayOfByte[6] = (byte)(arrayOfByte[6] & 0xF);
	    arrayOfByte[6] = (byte)(arrayOfByte[6] | 0x40);
	    arrayOfByte[8] = (byte)(arrayOfByte[8] & 0x3F);
	    arrayOfByte[8] = (byte)(arrayOfByte[8] | 0x80);
	    String uuid = uuidBuilder.newInstance(arrayOfByte).toString();
	    target = this.randoms.get(random.nextInt(this.randoms.size()));
	    
	    int start = this.start[target.nextInt(this.start.length)];
	    return uuid.substring(start, start+9);
	}
	
}
