package me.qwq.doghouse.controller.blog;

import me.qwq.doghouse.controller.common.BaseController;
import me.qwq.doghouse.entity.config.MailConfig;
import me.qwq.doghouse.service.*;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * 用户功能控制器
 *
 */
@Controller
@RequestMapping("/system")
public class VisitorController extends BaseController {
    
    static final String TOKEN_ERROR = "token 不存在或已被使用";
    
    static final String MAIL_DISABLED = "站点未开启邮件功能";
    
    static final String PATH = "system/unsubscribe-mail";

    @Autowired
    CommentService commentService;

    @Autowired
    ConfigService configService;
    
    @Autowired
    MailConfig mailConfig;
    
    @RequestMapping("/unsubscribe-mail")
    private String unsubscribeMailPost(String token) {
        
        String method = request.getMethod();
        
        if (!mailConfig.isMailOn()) {
            return render(MAIL_DISABLED, null);
        }
        
        if (StringUtils.isEmpty(token)) {
            return render(TOKEN_ERROR, null);
        }
        
        String mail = commentService.getUnsubscribeEmail(token);
        if (StringUtils.isEmpty(mail)) {
            return render(TOKEN_ERROR, null);
        }
        
        if ("GET".equals(method)) {
            return render(null, mail);
        }
        
        if ("POST".equals(method)) {
            if (commentService.unsubscribeByToken(token) == null) {
                return render(TOKEN_ERROR, null);
            }
            return render("操作成功", null);
        }

        return render("非法操作请求: " + method, null);
    }
    
    String render(String note, String mail) {
        request.setAttribute("note", note);
        request.setAttribute("mail", mail);
        return PATH;
    }
}
