package com.apobates.forum.bucket.smiley.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.apobates.forum.utils.Commons;
import com.google.gson.Gson;

//输出指定表情风格下的所有图片的URL
public class SmileyThemePictureServlet extends HttpServlet{
	private static final long serialVersionUID = -7533656883117984416L;
	private String smileyDirectName; 
	private String siteDomain; 
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String themeDirect = request.getParameter("theme");
		if(!Commons.isNotBlank(themeDirect)){
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "theme parameter lost");
			return;
		}
		String smileyThemePath = request.getServletContext().getRealPath(smileyDirectName + "/" + themeDirect + "/");
		List<String> data = Commons.queryFolderOfFileName(smileyThemePath, ".gif");
		data = data.stream().map(path -> siteDomain+smileyDirectName+"/"+themeDirect+"/"+path).collect(Collectors.toList());
		//
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		try(PrintWriter out = response.getWriter()){
			out.write(new Gson().toJson(data));
			out.flush();
		}
	}
	
	/**
	 * 获得初始化值
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.siteDomain = config.getInitParameter("siteDomain"); //站点URL, http://xx.com
		this.smileyDirectName = config.getInitParameter("directName"); //表情保存的目录
	}
}
