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.sql.Timestamp;
import java.util.regex.Matcher;

import dev.peerat.backend.model.Chapter;
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.JsonMap;

public class ChapterController{
	
	private DatabaseAdminRepository repo;
	
	public ChapterController(DatabaseRepository repo){
		this.repo = repo.getAdminRepository();
	}
	
	@Route(path = "^/admin/chapter/$", type = POST, needLogin = true)
	public void add(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		JsonMap json = reader.readJson();
		Chapter chapter = new Chapter(-1, json.get("name"), Timestamp.valueOf(json.<String>get("start")), Timestamp.valueOf(json.<String>get("end")));
		if(repo.adminAddChapter(chapter)){
			context.response(200);
		}else{
			context.response(501);
		}
	}
	
	@Route(path = "^/admin/chapter/(\\d+)$", type = DELETE, needLogin = true)
	public void delte(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		if(this.repo.adminDeleteChapter(Integer.parseInt(matcher.group(1)))){
			context.response(200);
		}else{
			context.response(501);
		}
	}
	
	@Route(path = "^/admin/chapter/(\\d+)$", type = PUT, needLogin = true)
	public void edit(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		JsonMap json = reader.readJson();
		Chapter chapter = new Chapter(-1, json.get("name"), Timestamp.valueOf(json.<String>get("start")), Timestamp.valueOf(json.<String>get("end")));
		if(repo.adminUpdateChapter(Integer.parseInt(matcher.group(1)), chapter)){
			context.response(200);
		}else{
			context.response(501);
		}
	}
	
	@Route(path = "^/admin/chapter/(\\d+)$", needLogin = true)
	public void get(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
		Chapter chapter = this.repo.getAdminChapter(Integer.parseInt(matcher.group(1)));
		JsonMap json = new JsonMap();
		json.set("name", chapter.getName());
		json.set("start", chapter.getStartDate());
		json.set("end", chapter.getEndDate());
		
		context.response(200);
		writer.write(json.toString()+"\n");
	}

}
