package bmserv.resources;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import bmserv.Server;
import bmserv.TemplateEngine;
import bmserv.model.Tag;
import bmserv.model.Tagging;

@Path("/tag")
public class TagResource {
	@GET
	@Path("/id/{tagid}")
	@Produces("text/xml")
	public bmserv.model.Tag getTagFromId(@PathParam("tagid") String tagid) {
		Tag t = Server.th.getTagFromId(tagid);
		return t;
	}
	
	@POST
	@Path("/create")
	@Produces("text/html")
	@Consumes("application/x-www-form-urlencoded")
	public String create(@FormParam("label") String label){
		Server.th.createTag(label);
		return TemplateEngine.redirect("/form/tag/add", 3, "Le tag a bien été créé. Vous allez être redirigé dans 3 secondes.");
	}	

	@GET
	@Path("/all")
	@Produces("text/xml")	
	public bmserv.model.handlers.TagHandler getAllTags() {
		return Server.th;
	}
	
	@GET
	@Path("/id/{tagid}/html")
	@Produces("text/html")
	public String getTagFromIdHtml(@Context HttpServletRequest req, @PathParam("tagid") String tagid) {
		TemplateEngine.setSession(req.getSession());
		Tag t = Server.th.getTagFromId(tagid);
		final StringBuilder sb = new StringBuilder();
		sb.append("\n<h1>Tag d&eacute;tail</h1>\n<h2>").append(t.getLabel()).append("</h2><ul>");
		List<Tagging> tglist=Server.tgh.getTaggingsFromTagId(tagid);
		for(Tagging tg : tglist){
			sb.append("<li>").append(tg.getBmId()).append("</li>");
		}
		sb.append("</ul>");
		return TemplateEngine.build(sb.toString());
	}

	@GET
	@Path("/all/html")
	@Produces("text/html")
	public String getAllTagsHtml(@Context HttpServletRequest req) {
		TemplateEngine.setSession(req.getSession());
		final StringBuilder sb = new StringBuilder();
		sb.append("<h1>Tags</h1>\n<table border='1' cellpadding='2' cellspacing='0' style='margin-top:10px'>");
		sb.append("\n<tr style='font-weight:bold;'><td>ID</td><td>Label</td></tr>");
		List<Tag> tlist = Server.th.getTags();
		for (Tag t : tlist) {
			sb.append("\n<tr><td>").append(t.getId()).append("</td><td>").append(t.getLabel()).append("</td></tr>");
		}
		sb.append("\n</table>");
		return TemplateEngine.build(sb.toString());
	}	
}
