package com.philisense.www.web;

import com.philisense.www.api.processor.VcodeProcessorFactory;
import com.philisense.www.enums.VcodeType;
import com.philisense.www.exception.UtilsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@RestController
public class VcodeDemoController {
    private static final Logger log = LoggerFactory.getLogger(VcodeDemoController.class);

    @Autowired
    private VcodeProcessorFactory vcodeProcessorFactory;

    /**
     *
     * @param vcodeGenType （imageCode | puzzleCaptcha | wordComb | smsCode）
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("vcode/gen/{vcodeGenType}")
    public void gen(@PathVariable String vcodeGenType, HttpServletRequest request, HttpServletResponse response) throws Exception{
        log.info("request url: {}, method:{}", request.getRequestURL(), request.getMethod());

        VcodeType codeType = VcodeType.get(vcodeGenType);

        if (codeType == null) {
            throw new UtilsException("系统不支持该校验码类型：" + vcodeGenType);
        } else {
            vcodeProcessorFactory.get(codeType).create(new ServletWebRequest(request, response));
        }
    }


    /**
     *
     * imageCode {vcodeType，vcodeKey，imageCode}
     * puzzleCaptcha {vcodeType，vcodeKey，x，width}
     * wordComb {vcodeType，vcodeKey，points}
     * smsCode {vcodeType，vcodeKey，smsCode}
     *
     * @param vcodeGenType （imageCode | puzzleCaptcha | wordComb | smsCode）
     * @param request
     * @param response
     * @return
     */
    @PostMapping("vcode/check/{vcodeGenType}")
    public String check(@PathVariable String vcodeGenType, HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("request url: {}, method:{}", request.getRequestURL(), request.getMethod());

            VcodeType codeType = VcodeType.get(vcodeGenType);

            if (codeType == null) {
                throw new UtilsException("系统不支持该校验码类型：" + vcodeGenType);
            } else {
                vcodeProcessorFactory.get(codeType).doValidate(new ServletWebRequest(request, response));
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return "成功";
    }
}