package dev.peerat.backend.routes;

import java.util.regex.Matcher;

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

public class DynamicLeaderboard extends Leaderboard{
	
	private Locker<Completion> locker;

	public DynamicLeaderboard(DatabaseRepository databaseRepo, Locker<Completion> locker){
		super(databaseRepo);
		this.locker = locker;
	}
	
	public Locker<Completion> getLocker(){
		return this.locker;
	}
	
	@RouteDoc(path = "/rleaderboard/{id}", responseCode = 101, responseDescription = "WebSocket")
	
	@Route(path = "^\\/rleaderboard\\/?(\\d+)?$", websocket = true)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		Key key = new Key();
		
		locker.init(key);
		try {
			while(!reader.isClosed()){
				locker.getValue(key);
				if(matcher.group(1) != null){
					groupsLeaderboard(Integer.parseInt(matcher.group(1)), writer);
				}else{
					playersLeaderboard(writer);
				}
				locker.lock(key);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		locker.remove(key);
	}
}