package me.qwq.doghouse.controller.blog.post;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import me.qwq.doghouse.entity.config.WikiConfig;
import me.qwq.doghouse.entity.Post;
import me.qwq.doghouse.pojo.bo.PostPassJar;
import me.qwq.doghouse.service.post.WikiService;
import me.qwq.doghouse.util.EscapeUnescapeUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.Cookie;

import java.util.ArrayList;
import java.util.List;


/**
 * PostTypeEnum.WIKI 前端分页控制器
 * @author Doghole
 */
@Controller
@Slf4j
@RequestMapping("/wiki")
public class WikiPaginationController extends AbstractPaginationController<WikiConfig, WikiService> {
    
    @Autowired
    ObjectMapper objectMapper;
    
    /**
     * 首页
     */
    public String index() {
        // 先找最顶层的一篇文章，如果有，跳转到顶层文章
        Post post = getPostTypeService().getOne(getPostTypeService().getWikiDefaultWrapper(isLogin()).last("LIMIT 1"));
        if (post != null) {
            return "redirect:" + post.getLink();
        }
        return super.index();
    }
    
    /**
     * Wiki 树形菜单点击
     * @param postId
     * @return
     * @throws JsonProcessingException 
     */
    @GetMapping({"/list", "/list/", "/list/{postId}"})
    public String listFrontWikisOnly(@PathVariable(name="postId", required=false) Long postId) throws JsonProcessingException {
        request.setAttribute("wikis", listFrontWikis(postId));
        return postTypeComponent.getTemplatePath(getPostType(), "side-only");
    }

    /**
     * 该方法不应通过 Web 接口调用，否则会暴露完整的 POST(WIKI)，包括密码
     * 放在控制器这里只是方便前端模板调用，并且能获得 service 的缓存能力
     * @param postId
     * @return
     * @throws JsonProcessingException 
     */
    public List<Post> listFrontWikis(Long postId) throws JsonProcessingException {
        List<Long> unfolded = WikiService.getUnfoldedWikis(request);
        String unfoldedStr = unfolded == null ? "[]" : objectMapper.writeValueAsString(unfolded);
        unfoldedStr = EscapeUnescapeUtils.escape(unfoldedStr);
        Cookie unfoldedCookie = new Cookie(WikiService.UNFOLDED_WIKIS, unfoldedStr);
        unfoldedCookie.setPath("/");
        response.addCookie(unfoldedCookie);
        // 清洗 Password
        Post post = getPostTypeService().getOne(getPostTypeService().getWikiDefaultWrapper(isLogin()).eq(Post::getPostId, postId));
        if (post != null && (!PostPassJar.validFromSession(session, post))) {
            return new ArrayList<>();
        }
        return getPostTypeService().listFrontWikis(postId, unfolded);
    }
    
}
