package cn.iselab.mooctest.user.service.impl;

import cn.iselab.mooctest.user.mapper.VerifyCodeDao;
import cn.iselab.mooctest.user.model.VerifyCode;
import cn.iselab.mooctest.user.service.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: xuexb
 * @Date: 2018.12.28 1:32
 */
@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    private VerifyCodeDao verifyCodeDao;

    @Override
    public VerifyCode getLatestVerifyCode(String type, String receiver) {
        return verifyCodeDao.findTop1ByTypeAndReceiverOrderByCreateTimeDesc(type, receiver);
    }

    @Override
    public VerifyCode saveVerifyCode(VerifyCode verifyCode) {
        return verifyCodeDao.save(verifyCode);
    }

    @Override
    public boolean validateVerifyCode(String type, String receiver, String code) {
        VerifyCode latestVerifyCode = getLatestVerifyCode(type, receiver);
        if (latestVerifyCode != null &&
                latestVerifyCode.getExpiredTime().getTime() > System.currentTimeMillis() &&
                (latestVerifyCode.getCode().equals(code))){
            return true;
        }
        return false;
    }
}
