package com.apobates.forum.trident.controller;

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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.ImageIOMeta;
import com.apobates.forum.core.api.service.TopicCarouselService;
import com.apobates.forum.core.api.service.TopicCarouselSlideService;
import com.apobates.forum.core.entity.TopicCarousel;
import com.apobates.forum.trident.vo.CarouselSlideItem;
/**
 * 轮播图控制器
 * 
 * @author xiaofanku
 * @since 20191103
 */
@Controller
@RequestMapping(value = "/topic/carousel")
public class TopicCarouselController {
	@Autowired
	private TopicCarouselService topicCarouselService;
	@Autowired
	private TopicCarouselSlideService topicCarouselSlideService;
	@Autowired
	private ImageIOMeta imageIOConfig;
	
	@GetMapping(path="/json")
	@ResponseBody
	public List<CarouselSlideItem> getCarouselPage(
			@RequestParam("title")String carouselTitle,
			HttpServletRequest request, 
			Model model){
		return topicCarouselSlideService.getAll(carouselTitle, imageIOConfig).map(CarouselSlideItem::new).collect(Collectors.toList());
	}
	
	@GetMapping(path="/{title}.xhtml")
	public String homePage(
			@PathVariable("title") String carouselTitle,
			HttpServletRequest request,
			Model model){
		Optional<TopicCarousel> data = topicCarouselService.get(carouselTitle, imageIOConfig);
		if(data.isPresent()){
			model.addAttribute("rs", data.get());
		}
		return "default/topic/carousel";
	}
	
	@GetMapping(path="/{volumes}-{board}.xhtml")
	public String boardPage(
			@PathVariable("volumes") int boardGroupId,
			@PathVariable("board") long boardId,
			HttpServletRequest request,
			Model model){
		Optional<TopicCarousel> data = topicCarouselService.get(boardGroupId, boardId, imageIOConfig);
		if(data.isPresent()){
			model.addAttribute("rs", data.get());
		}
		return "default/topic/carousel";
	}
	
	@GetMapping(path="/{volumes}-{board}.json")
	@ResponseBody
	public List<CarouselSlideItem> getBoardCarouselPage(
			@PathVariable("volumes") int boardGroupId,
			@PathVariable("board") long boardId,
			HttpServletRequest request, 
			Model model){
		Optional<TopicCarousel> data = topicCarouselService.get(boardGroupId, boardId, imageIOConfig);
		if(data.isPresent()){
			return data.get().getSlides().stream().map(CarouselSlideItem::new).collect(Collectors.toList());
		}
		return Collections.emptyList();
	}
}
