package dev.peerat.backend.routes.admins;

import java.util.regex.Matcher;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.Group;
import dev.peerat.backend.model.PeerAtUser;
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.Locker;
import dev.peerat.framework.Locker.Key;
import dev.peerat.framework.Response;
import dev.peerat.framework.Route;
import dev.peerat.framework.utils.json.JsonMap;

public class DynamicLogs implements Response{
	
	private Locker<Context> locker; //Context
	private DatabaseRepository repo;
	
	public DynamicLogs(Locker<Context> locker,  DatabaseRepository repo){
		this.locker = locker;
		this.repo = repo;
	}
	
	@RouteDoc(path = "/admin/logs", responseCode = 200, responseDescription = "L'utilisateur peux voir les logs en directe")
	@RouteDoc(responseCode = 401, responseDescription = "L'utilisateur n'a pas accès à cette ressource")

	@Route(path = "^/admin/logs$", needLogin = true, websocket = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		Group group = this.repo.getPlayerGroup(context.<PeerAtUser>getUser().getId(), 1);
		if(!group.getName().equalsIgnoreCase("Quarter-Master - Battles PAC x CEI")) return;
		
		Key key = new Key();
		
		locker.init(key);
		try {
			while(!reader.isClosed()){
				locker.lock(key);
				Context instance = locker.getValue(key);
				JsonMap json = new JsonMap();
				json.set("logged", instance.isLogged());
				if(instance.isLogged()) json.set("pseudo", repo.getPlayer(instance.<PeerAtUser>getUser().getId()).getPseudo());
				json.set("path", instance.getPath());
				json.set("type", instance.getType());
				json.set("code", instance.getResponseCode());
				
				writer.write(json.toString());
				writer.flush();
			}
		}catch(Exception e){}
		locker.remove(key);
	}

	
	
}
