package com.reptileclient.jlifeapp.service.impl;

import com.reptileclient.jlifeapp.service.DownLoadEmailDataService;
import com.reptileclient.jlifeapp.util.email.EmailProperties;
import com.reptileclient.jlifeapp.util.email.EmailUtils;

import lombok.extern.slf4j.Slf4j;


import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_PATTERN;

@Service
@Slf4j
public class DownLoadEmailDataServiceImpl implements DownLoadEmailDataService {


    @Resource
    private EmailProperties mailProperties;

    @Override
    public void downLoad() {
        String startDate = LocalDateTime.now().toLocalDate().atStartOfDay().format(DateTimeFormatter.ofPattern(NORM_DATETIME_PATTERN));
        String endDate = LocalDate.now().atStartOfDay().plusDays(1).format(DateTimeFormatter.ofPattern(NORM_DATETIME_PATTERN));
        downLoad(startDate, endDate);
    }

    @Override
    public void downLoad(String thisDay, String endDay) {
        try {
            if (StringUtils.isNotBlank(thisDay)) {
                EmailUtils.downLoad(mailProperties.getHost(), mailProperties.getEmail(), mailProperties.getPassword(), thisDay, endDay);
            } else {
                downLoad();
            }
        } catch (MessagingException | IOException | ParseException e) {
            log.error("下载{}天邮件内容失败，失败原因：{}", thisDay, e.getMessage());
        }

    }
}
