package be.jeffcheasey88.peeratcode.routes;

import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;

import java.util.regex.Matcher;

import org.json.simple.JSONObject;

import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
import be.jeffcheasey88.peeratcode.framework.Response;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.Router;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

public class Login implements Response {

	private DatabaseRepository databaseRepo;
	private Router router;

	public Login(DatabaseRepository databaseRepo, Router router) {
		this.databaseRepo = databaseRepo;
		this.router = router;
	}
	
	@RouteDoc(path = "/login", 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 = "^\\/login$", type = POST)
	public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
		if (user != null) {
			writer.response(403, "Access-Control-Allow-Origin: *");
			return;
		}
		JSONObject informations = reader.readJson();
		if (informations != null) {
			String pseudo = (String) informations.get("pseudo");
			String password = (String) informations.get("passwd");
			int id;
			if ((id = databaseRepo.login(pseudo, password)) >= 0) {
				writer.response(200, "Access-Control-Allow-Origin: *",
						"Access-Control-Expose-Headers: Authorization",
						"Authorization: Bearer " + this.router.createAuthUser(id));
				return;
			}
		}
		writer.response(400, "Access-Control-Allow-Origin: *");
	}

}
