package com.apobates.forum.trident.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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 com.apobates.forum.trident.OnlineDescriptor;
import com.apobates.forum.trident.exception.ResourceNotFoundException;
import com.apobates.forum.attention.core.ImagePathCoverter;
import com.apobates.forum.core.ad.ActiveDirectoryConnectorFactory;
import com.apobates.forum.core.api.ImageIOMeta;
import com.apobates.forum.core.api.service.BoardGroupService;
import com.apobates.forum.core.api.service.BoardService;
import com.apobates.forum.core.entity.BoardGroup;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.storage.core.MemberSessionBean;

/**
 * 版块组(卷)控制器
 * 
 * @author xiaofanku
 * @since 20190409
 */
@Controller
@RequestMapping(value = "/board/volumes")
public class BoardGroupController {
	@Autowired
	private BoardGroupService boardGroupService;
	@Autowired
	private BoardService boardService;
	@Autowired
	private ImageIOMeta imageIOConfig;
	@Value("${site.pageSize}")
	private int pageSize;
	private final static Logger logger = LoggerFactory.getLogger(BoardGroupController.class);
	
	@GetMapping(path="/{path}.xhtml")
	@OnlineDescriptor(action=ForumActionEnum.BOARD_GROUP_BROWSE)
	public String volumeHome(
			@PathVariable("path") String connectValue, 
			MemberSessionBean mbean, 
			HttpServletRequest request,
			Model model){
		BoardGroup bgObj = ActiveDirectoryConnectorFactory.build(BoardGroup.class, connectValue).orElseThrow(()->new ResourceNotFoundException("版块组/卷参数解析失败"));
		BoardGroup rs = boardGroupService.get(bgObj.getId()).orElseThrow(()->new ResourceNotFoundException("版块组(卷)不存在或暂时无法访问"));
		model.addAttribute("boardGroup", rs);
		//版块组下的版块
		model.addAttribute("boardes", boardService.getAllUsedByVolumesId(bgObj.getId()));
		return "default/volumes/index";
	}
	
	// 查看指定版块组的图标
	@GetMapping(path = "/ico/{id}.png", produces = MediaType.IMAGE_PNG_VALUE)
	public ResponseEntity<byte[]> getBoardVolumeIco(
			@PathVariable("id") int id, 
			HttpServletResponse response, 
			Model model) {
		BoardGroup bg = boardGroupService.get(id).orElse(null);
		if(null == bg){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return null;
		}
		try {
			String boardGroupIcoURL = new ImagePathCoverter(bg.getImageAddr())
								.decodeUploadImageFilePath(imageIOConfig.getImageBucketDomain(), imageIOConfig.getUploadImageDirectName())
								.orElse("/board/ico/default_icon.png");
			InputStream in = new URL(boardGroupIcoURL).openStream();
			byte[] avtarBytes = IOUtils.toByteArray(in);

			final HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.IMAGE_PNG);
			headers.setCacheControl(CacheControl.noCache().getHeaderValue());
			return new ResponseEntity<byte[]>(avtarBytes, headers, HttpStatus.CREATED);
		} catch (IOException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return null;
		}
	}
}
