package be.jeffcheasey88.peeratcode.routes;

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.Locker.Key;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Completion;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

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

	public DynamicLeaderboard(DatabaseRepository databaseRepo){
		super(databaseRepo);
		this.locker = new 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, User user, 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);
	}
}