package me.qwq.doghouse.controller.api.v2;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;

import me.qwq.dogface.Dogface;
import me.qwq.doghouse.controller.common.BaseController;
import me.qwq.doghouse.entity.Comment;
import me.qwq.doghouse.exception.RException;
import me.qwq.doghouse.pojo.dto.R;
import me.qwq.doghouse.service.CommentService;
import me.qwq.doghouse.service.StatisticsService;
import me.qwq.doghouse.util.GravatarUtils;
import me.qwq.doghouse.util.MarkDownUtils;
import me.qwq.doghouse.util.SessionUtils;

@RestController
@RequestMapping("/api/v2/comment")
public class CommentApiControllerV2 extends BaseController {
    
    @Autowired
    StatisticsService statisticsService;
    
    @Autowired
    GravatarUtils gravatarUtils;
    
    @Autowired
    CommentService commentService;
    
    @Autowired
    Dogface dogface;

    @PostMapping("/preview")
    public R<?> preview(@RequestBody JsonNode jo) {
        String markDown = MarkDownUtils.commentToHtml(jo.get("content").asText());
        return R.ok(markDown);
    }
    
    @GetMapping("/getContentSource/{id}")
    public R<?> getContentSource(@PathVariable("id") Long id) {
        if (!isLogin() && !SessionUtils.containsCommentId(session, id)) {
            throw RException.unauthorized("非法请求");
        }
        Comment commentForEdit = commentService.getById(id);
        if (commentForEdit == null) {
            // 这一般不会进来，除非是管理员
            throw RException.badRequest("非法请求");
        }
        
        Map<String, Object> dto = new HashMap<>();
        dto.put("author", commentForEdit.getAuthor());
        dto.put("isMarkdown", commentForEdit.isMarkdown());
        dto.put("email", commentForEdit.getEmail());
        dto.put("url", commentForEdit.getUrl());
        dto.put("content", commentForEdit.getContent());
        dto.put("subscribeReply", commentForEdit.isSubscribeReply());
        dto.put("commentStatu", commentForEdit.getCommentStatus());
        dto.put("id", commentForEdit.getId());
        
        return R.ok(dto);
    }
}
