package be.jeffcheasey88.peeratcode.routes.groups;

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

import java.time.LocalDateTime;
import java.util.regex.Matcher;

import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
import be.jeffcheasey88.peeratcode.framework.Locker;
import be.jeffcheasey88.peeratcode.framework.Response;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Chapter;
import be.jeffcheasey88.peeratcode.model.Completion;
import be.jeffcheasey88.peeratcode.model.Group;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

public class GroupQuit implements Response{
	
	private DatabaseRepository repo;
	private int groupDelay;
	
	private final Locker<Completion> leaderboard;

	public GroupQuit(DatabaseRepository repo, int groupDelay, Locker<Completion> locker){
		this.repo = repo;
		this.groupDelay = groupDelay;
		
		this.leaderboard = locker;
	}
	
	@RouteDoc(path = "/groupQuit", responseCode = 200, responseDescription = "L'utilisateur à quitter le groupe")
	@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur n'est pas dans le groupe / n'a pas pu le quittez")
	@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de quitter un groupe après le délai maximum de création de l'event")
	
	@Route(path = "^\\/groupQuit$", type = POST, needLogin = true)
	public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
		Group group = new Group(reader.readJson());
		
		Group userGroup = this.repo.getPlayerGroup(user.getId(), group.getLinkToChapter());
		if(!group.equals(userGroup)){
			writer.response(403, "Access-Control-Allow-Origin: *");
			return;
		}
		
		if(group.getLinkToChapter() != null){
			Chapter chapter = this.repo.getChapter(group.getLinkToChapter());
			if(chapter.getStartDate() != null){
				LocalDateTime start = chapter.getStartDate().toLocalDateTime().plusMinutes(this.groupDelay);
				if(LocalDateTime.now().isAfter(start)){
					writer.response(423, "Access-Control-Allow-Origin: *");
					return;
				}
			}
		}
		
		if (this.repo.leaveGroup(group, user)) {
			writer.response(200, "Access-Control-Allow-Origin: *");
			
			leaderboard.setValue(new Completion(0, 0, 0, null, 0));
		} else {
			writer.response(403, "Access-Control-Allow-Origin: *");
		}
	}
	
}
