package com.apobates.forum.trident.controller;

import java.util.List;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.text.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.core.api.service.SmileyThemeService;
import com.apobates.forum.trident.smiley.SmileyStorage;
/**
 * 表情图标
 * @deprecated 改用Emoji而停止使用
 * 
 * @author xiaofanku@live.cn
 * @since 20170516
 */
@Controller
@RequestMapping(value = "/smiley")
public class SmileyController {
	@Autowired
	private SmileyThemeService smileyThemeService;
	@Autowired
	private SmileyStorage smileyStorage;
	@Value("${site.domain}")
	private String siteDomain;
	
	//单页发布话题[|回复]页中的列出目录下的所有表情图标
	@GetMapping(path="/list.xhtml")
	public String getDirect(
			@RequestParam(value = "tyle", required = false) String directParam, 
			HttpServletRequest request, 
			Model model) {
		//---------------------------------------------是否来源自本站
		String requestRefString = request.getHeader("referer");
		if (null==requestRefString || !requestRefString.startsWith(siteDomain)) { // 只允许本站连接
			return "default/common/illegal_embed";
		}
		//---------------------------------------------
		//获得风格定义
		//key=表情风格目录名, value=中文文字描述
		TreeMap<String,String> themesMap = smileyThemeService.getAllUsed();
		if(themesMap.isEmpty()) {
			List<String> smileyThemes = smileyStorage.getThemeDirectNames(); //需要取到所有的目录名 
			themesMap = smileyThemes.stream()
									.collect(Collectors.toMap(
												Function.identity(), 
												s->WordUtils.capitalize(s), 
												(oldDirectName, newDirectName)->newDirectName, 
												TreeMap::new));//qq->Qq
		}
		model.addAttribute("smileyThemesMap", themesMap);
		//默认激活哪个风格
		String defaultSmiley = themesMap.keySet().stream().findFirst().get();
		model.addAttribute("activeTheme", defaultSmiley);
		return "default/common/smiley";
	}
	
	// Embed快速回复中的加载指定表情风格下的图片
	@GetMapping(path="/pic", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<String> getThemePicture(
			@RequestParam("theme")String themeDirectName, 
			HttpServletRequest request, 
			Model model){
		return smileyStorage.getThemePictures(themeDirectName);
	}
}
