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.Group;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

public class GroupCreate implements Response {

	private Locker<Group> locker;
	private DatabaseRepository repo;
	private int groupDelay;

	public GroupCreate(DatabaseRepository repo, Locker<Group> locker, int groupDelay){
		this.repo = repo;
		this.locker = locker;
		this.groupDelay = groupDelay;
	}

	@RouteDoc(path = "/groupCreate", responseCode = 200, responseDescription = "Le groupe a été créé")
	@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est déjà dans le groupe / ne peux pas le rejoindre")
	@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de crée un groupe après le délai maximum de création de l'event")
	
	@Route(path = "^\\/groupCreate$", type = POST, needLogin = true)
	public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
		Group newGroup = new Group(reader.readJson());
		
		if (this.repo.getPlayerGroup(user.getId(), newGroup.getLinkToChapter()) == null) {
			try {
				if(this.repo.getGroupId(newGroup) == null) throw new NullPointerException();
				writer.response(403, "Access-Control-Allow-Origin: *");
				return;
			}catch(NullPointerException e){
				if(newGroup.getLinkToChapter() != null){
					Chapter chapter = this.repo.getChapter(newGroup.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.insertGroup(newGroup, user)) {
					writer.response(200, "Access-Control-Allow-Origin: *");
					
					locker.setValue(newGroup);
				} else {
					writer.response(403, "Access-Control-Allow-Origin: *");
				}
			}
		}else {
			writer.response(403, "Access-Control-Allow-Origin: *");
		}
	}
}
