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.HashMap;
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.model.PeerAtUser;
import dev.peerat.backend.repository.DatabasePlayerRepository;
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.Router;
import dev.peerat.framework.utils.json.JsonMap;

public class ForgotPassword extends FormResponse{

	private Router<PeerAtUser> router;
	private DatabasePlayerRepository repo;
	private Mail mail;
	private Map<String, String> codes;
	private List<Random> randoms;
	
	public ForgotPassword(Router<PeerAtUser> router, DatabaseRepository repo, Mail mail){
		this.router = router;
		this.repo = repo.getPlayerRepository();
		this.mail = mail;
		this.codes = new HashMap<>();
		
		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();
		}
	}

	@Route(path = "^/user/fpw$", 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");
		
		int player = repo.getPlayerId(email);
		if(player < 0){
			context.response(400);
			return;
		}
		
		if(hasFields("code") && areValids("password")){
			String checkCode = codes.get(email);
			if(checkCode == null){
				context.response(400);
				return;
			}
			
			String code = json.<String>get("code");
			String password = json.get("password");
			
			if(checkCode.equals(code)){
				codes.remove(email);
				
				repo.updatePassword(player, password);
				context.response(200,
						"Access-Control-Expose-Headers: Authorization",
						"Authorization: Bearer " + this.router.createAuthUser(new PeerAtUser(player)));
			}else{
				context.response(400);
			}
		}else{
			String code = codeGenerator();
			codes.put(email, code);
			mail.send(email, "Forgot your Peer @ Code password ?", "Your check code is "+code+" !");
			context.response(200);
		}
	}
	
	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);
	}

}
