package dev.peerat.backend.routes.admins;

import java.util.regex.Matcher;

import org.json.simple.JSONObject;

import dev.peerat.backend.bonus.extract.RouteDoc;
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;

public class DynamicLogs implements Response{
	
	private Locker<Context> locker; //Context
	private DatabaseRepository repo;
	
	public DynamicLogs(DatabaseRepository repo, Locker<Context> locker){
		this.repo = repo;
		this.locker = locker;
	}
	
	@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$", websocket = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		//check if admin
		
		Key key = new Key();
		
		locker.init(key);
		try {
			while(!reader.isClosed()){
				locker.lock(key);
				Context instance = locker.getValue(key);
				JSONObject json = new JSONObject();
				json.put("logged", instance.isLogged());
				if(instance.isLogged()) json.put("pseudo", repo.getPlayer(instance.<PeerAtUser>getUser().getId()).getPseudo());
				json.put("path", instance.getPath());
				json.put("type", instance.getType());
				json.put("code", instance.getResponseCode());
				
				writer.write(json.toJSONString());
				writer.flush();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		locker.remove(key);
	}

	
	
}
