package be.jeffcheasey88.peeratcode.routes.groups;

import java.util.regex.Matcher;

import org.json.simple.JSONArray;

import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
import be.jeffcheasey88.peeratcode.framework.Response;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Group;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;

public class GroupList implements Response {

	private DatabaseRepository repo;

	public GroupList(DatabaseRepository repo) {
		this.repo = repo;
	}
	
	@RouteDoc(path = "/groups", responseCode = 200, responseDescription = "JSON avec la liste des groups")

	@Route(path = "^\\/groups$", needLogin = true)
	public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
		writer.response(200, "Access-Control-Allow-Origin: *");
		JSONArray result = new JSONArray();
		for(Group group : this.repo.getAllGroups()) result.add(group.toJson());
		writer.write(result.toJSONString());
	}

}
