package com.philisense.www.api.processor.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.philisense.www.api.generator.impl.ImageCodeGenerator;
import com.philisense.www.api.processor.AbstractVcodeProcessor;
import com.philisense.www.consts.ErrorConst;
import com.philisense.www.dto.ImageCode;
import com.philisense.www.enums.VcodeType;
import com.philisense.www.exception.UtilsException;
import com.philisense.www.utils.ImageConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class ImageCodeProcessor extends AbstractVcodeProcessor<ImageCode> {

    @Resource
    private ObjectMapper objectMapper;

    public ImageCodeProcessor(ImageCodeGenerator vcodeGenerator) {
        super(VcodeType.IMAGE_CODE, vcodeGenerator);
    }

    @Override
    protected void preValidate(ServletWebRequest request) throws UtilsException {
        String code = request.getParameter("imageCode");
        if (StringUtils.isBlank(code)) {
            throw new UtilsException("imageCode不能为空", ErrorConst.ERR_CODE);
        }
    }

    @Override
    protected void validate(ServletWebRequest request, Object savedValue) throws UtilsException {
        String code = request.getParameter("imageCode");
        if (!StringUtils.equals(code, (String) savedValue)) {
            throw new UtilsException("图片验证码校验失败", ErrorConst.ERR_CODE);
        }
    }

    @Override
    protected void send(ServletWebRequest request, ImageCode imageCode) throws Exception {
        HttpServletResponse response = request.getResponse();
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "生成成功！");
        Map<String, Object> data = new HashMap<>();
        data.put("image", ImageConvertUtils.toDataUri(imageCode.getImage(), "png"));
        data.put("vcodeKey", imageCode.getKey());
        result.put("data", data);
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
