package com.mca.cmmn.service;

import com.mca.cmmn.mapper.UserCertificationMapper;
import com.mca.cmmn.vo.UserCertificationVO;
import com.mca.user.vo.UserVO;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.mail.MailException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Random;

@Service("userCertificationService")
public class UserCertificationService {

  @Resource(name = "userCertificationMapper")
  UserCertificationMapper userCertificationMapper;

  public String sendCertificationNumber(UserVO user) throws MailException {
    Random random = new Random(System.currentTimeMillis());
    int range = (int)Math.pow(10,6);
    int trim = (int)Math.pow(10, 6-1);
    int certificationNumber = random.nextInt(range)+trim;

    UserCertificationVO userCertificationVO = new UserCertificationVO();
    userCertificationVO.setUserid(user.getUserid());
    userCertificationVO.setCertification_num(Integer.toString(certificationNumber));
    userCertificationVO.setExpiration_date(LocalDateTime.now().plusMinutes(5));
    userCertificationMapper.insertCertificationNum(userCertificationVO);

    SimpleEmail email = new SimpleEmail();
    email.setCharset("euc-kr");
    email.setHostName("smtp.naver.com");
    email.setSmtpPort(587);
    email.setAuthentication("dbnt0928", "andy002c?");
    try {
      email.addTo(user.getEmail(), user.getName());
      email.setFrom("dbnt0928@naver.com", "[지하공간]인증번호 발송");
      email.setSubject("[지하공간]인증번호 발송");
      email.setContent("인증번호 : "+certificationNumber, "text/plain; charset=euc-kr");
      email.send();
    } catch (EmailException e) {
      e.printStackTrace();
      return "mailError";
    }
    return "mailSend";
  }

  public UserCertificationVO selectCertificationInfo(UserCertificationVO certificationVO) {
    return userCertificationMapper.selectCertificationInfo(certificationVO);
  }

  public void updateCertificationNumStatus(UserCertificationVO certificationVO) {
    userCertificationMapper.updateCertificationNumStatus(certificationVO);
  }
}
