package dev.peerat.backend.routes.users;

import java.util.regex.Matcher;

import org.json.simple.JSONObject;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.PeerAtUser;
import dev.peerat.backend.model.Player;
import dev.peerat.backend.repository.DatabaseRepository;
import dev.peerat.framework.Context;
import dev.peerat.framework.HttpReader;
import dev.peerat.framework.HttpWriter;
import dev.peerat.framework.RequestType;
import dev.peerat.framework.Response;
import dev.peerat.framework.Route;

public class ProfileSettings implements Response{
	
	private DatabaseRepository repo;
	
	public ProfileSettings(DatabaseRepository repo){
		this.repo = repo;
	}

	@RouteDoc(path = "/user/settings", responseCode = 200, responseDescription = "L'utilisateur a mis à jours sont profile")
	@RouteDoc(responseCode = 400, responseDescription = "L'utilisateur a envoyer une donnée unique, déjà utilisée")
	
	@Route(path = "^/user/settings$", type = RequestType.POST, needLogin = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		JSONObject json = reader.readJson();
		
		String pseudo = (String) json.get("pseudo");
		String email = (String) json.get("email");
		String firstname = (String) json.get("firstname");
		String lastname = (String) json.get("lastname");
		Player player = repo.getPlayer(context.<PeerAtUser>getUser().getId());
		
		if(!player.getPseudo().equals(pseudo)){
			if(!repo.updatePseudo(context.<PeerAtUser>getUser().getId(), player, pseudo)){
				context.response(400);
				return;
			}
			player.setPseudo(pseudo);
		}
		
		if(!player.getEmail().equals(email)){
			
		}
		
		if((!player.getFirstname().equals(firstname)) || (!player.getLastname().equals(lastname))){
			repo.updateProfile(context.<PeerAtUser>getUser().getId(), player, lastname, firstname);
		}
		
		context.response(200);
	}

}
