package com.apobates.forum.trident.controller;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
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 com.apobates.forum.core.api.service.TopicService;
import com.apobates.forum.core.api.service.TopicTagSHistoryService;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.event.elderly.ActionEventCulpritor;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.trident.OnlineDescriptor;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
/**
 * 搜索控制器
 * 
 * @author xiaofanku
 * @since 20200114
 */
@Controller
@RequestMapping(value = "/search")
public class TopicSearchController {
	@Autowired
	private TopicService topicService;
	@Autowired
	private TopicTagSHistoryService topicTagSHistoryService;
	@Value("${site.pageSize}")
	private int pageSize;
	
	// 
	@GetMapping(path="/")
	@OnlineDescriptor(action=ForumActionEnum.TOPIC_SEARCH)
	public String searchHome(
			@RequestParam("word")String searchWord, 
			@RequestParam(value = "token", required = false, defaultValue = "0")String token, 
			@RequestParam(value = "p", required = false, defaultValue = "1") int page, 
			MemberSessionBean mbean,
			HttpServletRequest request, 
			Model model){
		List<String> sw = Optional.ofNullable(searchWord).map(str->Arrays.asList(str.split(" "))).orElse(Collections.emptyList());
		String topicLink = String.format("%s/search/", request.getContextPath());
		FrontPageURL fpbuild = new FrontPageURL(topicLink).addPageSize("number", pageSize).addParameter("word", searchWord);
		Pageable pr = new PageRequest(page, fpbuild.getPageSize());
		
		Page<Topic> rs = topicService.getAllForTag(sw, pr); 
		model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
		model.addAttribute("pageData", pr.toData(fpbuild, rs.getTotalElements()));
		if(1 == page){
			ActionEventCulpritor aec = ActionEventCulpritor.getInstance(mbean.getMid(), mbean.getNickname(), request, token);
			topicTagSHistoryService.create(searchWord, rs.getTotalElements(), aec);
		}
		model.addAttribute("pageTitle", "话题搜索 p"+page);
		return "default/search/index";
	}
}
