package com.reptileclient.jlifeapp.listener;

import com.reptileclient.jlifeapp.util.OkHttpUtil;
import com.reptileclient.jlifeapp.util.email.EmailUtils;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Properties;


@Service
@Slf4j
public class ALiEmailListener {


    private IMAPFolder imapFolder;

    private final String aliFromSuffix = "shaoyixiang@lifejingzhi.com,wangjiangyun@lifejingzhi.com,18451328122@163.com";


    //开启监听
    @SneakyThrows
    public void init() {
        new Thread(() -> new ALiEmailListener().startService()).start();
    }

    public void startService() {
        try {
            setup();
        } catch (MessagingException e) {
            System.out.println("Error configuring imap server:");
            System.exit(1);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }


        imapFolder.addMessageCountListener(new MessageCountListener() {


            public void messagesAdded(MessageCountEvent arg0) {
                for (Message message : arg0.getMessages()) {
                    Address[] from;
                    try {
                        from = message.getFrom();
                    } catch (MessagingException e) {
                        throw new RuntimeException(e);
                    }
                    if (from != null) {
                        String[] emails = aliFromSuffix.split(",");
                        for (Address address : from) {
                            // 要求emails和给的地址一致
                            if (Arrays.stream(emails).anyMatch(a -> a.equals(address.toString()))) {
                                System.out.println("New message from " + address);
                                try {
                                    if (EmailUtils.isContainAttach(message)) {
                                        System.out.println("start to process email with attachment");
                                        EmailUtils.saveAttachMent(message);
                                        //检查是否有success.txt 文件在目录下，有则调用report服务写入数据库
                                        String fileDir = EmailUtils.getFileDir();
                                        boolean exist = EmailUtils.isFileExist(fileDir + "success.txt");
                                        while (!exist) {
                                            Thread.sleep(1000 * 8);
                                            exist = EmailUtils.isFileExist(fileDir + "success.txt");
                                        }
                                        log.info("本地处理完毕，调用report服务写入数据到数据库");
                                        String url = "https://servant.lifejingzhi.com/reportservice/syncMail";
                                        Request request = new Request.Builder().url(url).build();
                                        OkHttpUtil.get(request);
                                        log.info("调用report服务写入数据到数据库完毕");
                                    }
                                } catch (MessagingException | IOException | InterruptedException e) {
                                    System.out.println(e.getMessage());
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void messagesRemoved(MessageCountEvent arg0) {
                System.out.println("Message was removed.");
            }

        });

        for (; ; ) {
            try {
                imapFolder.idle();
            } catch (Exception e) {
                try {
                    Thread.sleep(1000 * 3);
                    startService();
                } catch (InterruptedException ignored) {

                }
            }
        }
    }


    private void setup() throws MessagingException, GeneralSecurityException {
        Properties props = new Properties();
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imaps.ssl.enable", "true");
        props.setProperty("mail.imaps.connectiontimeout", "10000");
        props.setProperty("mail.imaps.timeout", "10000");
        props.put("mail.imaps.ssl.socketFactory", sf);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore();

        store.connect("imap.qiye.aliyun.com", 143, "documents@lifejingzhi.com", "JZSHjzsh123456");
        imapFolder = (IMAPFolder) store.getFolder("INBOX");
        System.out.println("start listen email ~~~~");
        imapFolder.open(Folder.READ_WRITE);
    }

}
