package dev.peerat.backend.routes;

import java.util.regex.Matcher;

import dev.peerat.framework.Context;
import dev.peerat.framework.HttpReader;
import dev.peerat.framework.HttpWriter;
import dev.peerat.framework.Injection;
import dev.peerat.framework.Locker;
import dev.peerat.framework.Locker.Key;
import dev.peerat.framework.Route;
import dev.peerat.framework.utils.json.JsonMap;

public class EventSSE{
	
	private Locker<GroupMessage> locker;
	
	public EventSSE(@Injection("groupMessages") Locker<GroupMessage> locker){
		this.locker = locker;
	}
	
	@Route(path = "^/group/event/$", websocket = true)
	public void connect(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		String group = reader.<JsonMap>readJson().get("group");
		
		Key key = new Key();
		
		locker.init(key);
		try {
			while(true){
				locker.lock(key);
				GroupMessage message = locker.getValue(key);
				if(message.getGroup() == null || message.getGroup().equals(group)){
					JsonMap send = new JsonMap();
					send.set("message", message.getMessage());
					writer.write(send.toString()+"\n");
					writer.flush();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		locker.remove(key);
	}

	public static class GroupMessage{
		
		private String group;
		private String message;
		
		public GroupMessage(String group, String message){
			this.group = group;
			this.message = message;
		}
		
		public String getGroup(){
			return this.group;
		}
		
		public String getMessage(){
			return this.message;
		}
		
	}
}
