package com.philisense.www.api.processor;

import com.philisense.www.api.generator.VcodeGenerator;
import com.philisense.www.api.repository.VcodeRepository;
import com.philisense.www.dto.Vcode;
import com.philisense.www.enums.VcodeType;
import com.philisense.www.exception.UtilsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.ServletWebRequest;

public abstract class AbstractVcodeProcessor<C extends Vcode> implements VcodeProcessor {

    private VcodeGenerator vcodeGenerator;

    // 记录校验码类型
    private VcodeType vcodeType;

    @Autowired
    private VcodeRepository vcodeRepository;

    public AbstractVcodeProcessor(VcodeType vcodeType, VcodeGenerator vcodeGenerator) {
        this.vcodeType = vcodeType;
        this.vcodeGenerator = vcodeGenerator;
    }

    @Override
    public void create(ServletWebRequest request) throws Exception {
        C vcode = (C)vcodeGenerator.generate(request);
        String key = vcodeRepository.save(request, extractVcodeValueToBeSaved(vcode), vcodeType);
        vcode.setKey(key);
        send(request, vcode);
    }

    @Override
    public void doValidate(ServletWebRequest request) throws UtilsException {

        preValidate(request);

        Object savedValue = vcodeRepository.get(request, vcodeType);

        validate(request, savedValue);

        vcodeRepository.remove(request, vcodeType);
    }

    protected abstract void preValidate(ServletWebRequest request) throws UtilsException;

    protected abstract void validate(ServletWebRequest request, Object savedValue) throws UtilsException;

    /**
     * 默认的实现，子类可以覆盖，比如图片滑动验证码获取的是x
     * @param vcode
     * @return
     */
    protected Object extractVcodeValueToBeSaved(C vcode) {
        return vcode.getCode();
    }

    protected abstract void send(ServletWebRequest request, C vcode) throws Exception;
}
