package com.apobates.forum.thrones.admin.controller;

import com.apobates.forum.core.ImageIOMeta;
import java.util.ArrayList;
import java.util.List;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
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.entity.Album;
import com.apobates.forum.core.entity.AlbumPicture;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.core.service.AlbumPictureService;
import com.apobates.forum.core.service.AlbumService;
import com.apobates.forum.core.service.TopicService;
import com.apobates.forum.thrones.admin.controller.form.AlbumPictureForum;
import com.apobates.forum.thrones.admin.exception.ResourceNotFoundException;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
import java.util.Optional;

/**
 * 话题像册控制器
 *
 * @author xiaofanku
 * @since 20190407
 */
@Controller
@RequestMapping(value = "/topic/album")
public class AdminAlbumController {
    @Autowired
    private AlbumService albumService;
    @Autowired
    private AlbumPictureService albumPictureService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private ImageIOMeta imageIOMeta;
    @Value("${site.pageSize}")
    private int pageSize;
    // 所有的话题像册列表
    @GetMapping(path = "/")
    public String listPage(
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            HttpServletRequest request,
            Model model) {
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/topic/album/").addPageSize("number", pageSize);
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<Album> rs = albumService.getAll(pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", fpbuild.toPageData(pr, rs.getTotalElements()));
        return "admin/album/index";
    }
    
    // 话题的图片列表
    @GetMapping(path = "/picture")
    public String getAlbumPicture(
            @RequestParam("topic") long topicId,
            HttpServletRequest request,
            Model model) {
        //像册->图片
        Optional<Album> topicAlbum = albumService.getByTopic(topicId);
        if (!topicAlbum.isPresent()) {
            return "admin/album_picture/index";
        }
        Album album = topicAlbum.get();
        model.addAttribute("album", album);
        List<AlbumPicture> pictures = new ArrayList<>();
        pictures.addAll(albumPictureService.getAll(album.getId()).collect(Collectors.toList()));
        model.addAttribute("rs", pictures);
        return "admin/album_picture/index";
    }
    
    // 为话题像册添加图片 | 话题没像册时album=0
    @GetMapping(path = "/picture/add")
    public String addAlbumPictureForm(
            @RequestParam("topic") long topicId,
            @RequestParam(value = "album", required = false, defaultValue = "0") long topicAlbumId,
            HttpServletRequest request,
            Model model) {
        Topic topic = topicService.get(topicId).orElseThrow(()->new ResourceNotFoundException("话题不存在或暂时无法访问"));
        model.addAttribute("topic", topic);
        AlbumPictureForum form = new AlbumPictureForum();
        form.setAlbumId(topicAlbumId + "");
        form.setTopicId(topicId + "");
        form.setCaption("");
        form.setStatus(true);
        model.addAttribute("form", form);
        return "admin/album_picture/add";
    }
    
    @PostMapping(path = "/picture/add")
    public String addAlbumPictureAction(
            @ModelAttribute("form") AlbumPictureForum form,
            HttpServletRequest request,
            Model model) {
        Topic topic = topicService.get(form.getLongTopicId()).orElseThrow(()->new ResourceNotFoundException("话题不存在或暂时无法访问"));
        //------------------------------------------------------------编码图标图片的地址
        String imageAddr = form.getEncodePictureAddr(imageIOMeta).orElse(null);
        if(null == imageAddr){
            model.addAttribute("errors", "缺少图片地址");
            model.addAttribute("form", form);
            return "admin/album_picture/add";
        }
        //------------------------------------------------------------
        long albumId = form.getLongAlbumId();
        boolean symbol;
        if (albumId > 0) {
            symbol = albumPictureService.create(albumId, imageAddr, form.getCaption(), form.getIntegerRanking(), form.getBooleanStatus()).isPresent();
        } else {
            symbol = albumService.create(imageAddr, form.getCaption(), form.getBooleanStatus(), topic) >0;
        }
        if (symbol) {
            return "redirect:/topic/album/picture?topic=" + form.getTopicId();
        }
        model.addAttribute("errors", "添加图片操作失败");
        model.addAttribute("form", form);
        return "admin/album_picture/add";
    }
    // 设置某图片为指定话题像册的封面
    @PostMapping(path = "/cover", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage setupTopicAlbumCoverAction(
            @RequestParam("album") long topicAlbumId,
            @RequestParam("cover") long coverPictureId,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.take(()->albumService.editCover(topicAlbumId, coverPictureId)).success("封面图片设置成功").error("操作失败");
    }
}