package dev.peerat.backend.routes.users;

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

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

import dev.peerat.backend.model.PeerAtUser;
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 DatabaseRepository repo;
	private Mail mail;
	private Map<String, Integer> codes;
	
	public ForgotPassword(Router<PeerAtUser> router, DatabaseRepository repo, Mail mail){
		this.router = router;
		this.repo = repo;
		this.mail = mail;
		this.codes = new HashMap<>();
	}

	@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")){
			Integer checkCode = codes.get(email);
			if(checkCode == null){
				context.response(400);
				return;
			}
			
			int code = json.<Number>get("code").intValue();
			String password = json.get("password");
			
			if(code == checkCode.intValue()){
				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{
			int code = codeGenerator();
			codes.put(email, code);
			mail.send(email, "Forgot your Peer @ Code password ?", "Your check code is "+code+" !");
			context.response(200);
		}
	}
	
	private int codeGenerator(){
		int min = 1000;
		int max = 9999;
		return new Random().nextInt((max-min)) + min;

	}

}
