package dev.peerat.backend.routes.admins;

import static dev.peerat.framework.RequestType.DELETE;
import static dev.peerat.framework.RequestType.POST;
import static dev.peerat.framework.RequestType.PUT;

import java.util.List;
import java.util.regex.Matcher;

import dev.peerat.backend.model.Tag;
import dev.peerat.backend.repository.DatabaseAdminRepository;
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.Route;
import dev.peerat.framework.utils.json.JsonArray;
import dev.peerat.framework.utils.json.JsonMap;

public class TagController {
	
	private DatabaseAdminRepository repo;
	
	public TagController(DatabaseRepository repo){
		this.repo = repo.getAdminRepository();
	}
	
	@Route(path = "^/admin/tag/$", type = POST, needLogin = true)
	public void add(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		JsonMap json = reader.readJson();
		if(repo.adminAddTag(json.get("name"))){
			context.response(200);
		}else{
			context.response(501);
		}
	}
	
	@Route(path = "^/admin/tag/(\\d+)$", type = DELETE, needLogin = true)
	public void delete(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		if(this.repo.adminDeleteTag(Integer.parseInt(matcher.group(1)))){
			context.response(200);
		}else{
			context.response(501);
		}
	}
	
	@Route(path = "^/admin/tag/(\\d+)$", type = PUT, needLogin = true)
	public void edit(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		JsonMap json = reader.readJson();
		if(repo.adminUpdateTag(new Tag(Integer.parseInt(matcher.group(1)), json.get("name")))){
			context.response(200);
		}else{
			context.response(501);
		}
	}
	
	@Route(path = "^/admin/tag/$", needLogin = true)
	public void get(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		List<Tag> list = repo.getAdminTags();
		JsonArray json = new JsonArray();
		for(Tag tag : list) json.add(tag.toJson());
		context.response(200);
		writer.write(json.toString());
		writer.flush();
	}
	

}
