package com.fjhx.mail.util;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;

import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Session;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

public class EmailUtil {

    private static final HashMap<String, String> ImapStoreId = new HashMap<>();

    static {
        ImapStoreId.put("name", "fjhx");
        ImapStoreId.put("version", "1.0.0");
        ImapStoreId.put("vendor", "fjhxClient");
        ImapStoreId.put("support-email", "fjhx@fjhx.com");
    }

    /**
     * 获取imapStore
     * 993
     */
    public static IMAPStore getIMAPStore(String host, Integer port, String user, String password) throws MessagingException {
        Properties ImapProperties = new Properties();
        ImapProperties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        Session session = Session.getInstance(ImapProperties);
        IMAPStore store = (IMAPStore) session.getStore("imap");
        store.connect(host, port, user, password);
        store.id(ImapStoreId);
        return store;
    }

    /**
     * 获取邮箱文件夹
     */
    public static List<String> getFolderNameList(IMAPStore imapStore) throws MessagingException {
        IMAPFolder folder = (IMAPFolder) imapStore.getDefaultFolder();
        Folder[] folders = folder.list();
        List<String> mailFolderList = new ArrayList<>();
        addMailFolderList(mailFolderList, folders);
        return mailFolderList;
    }

    private static void addMailFolderList(List<String> mailFolderList, Folder[] folders) throws MessagingException {
        for (Folder folder : folders) {
            int type = folder.getType();
            if (type == 2) {
                addMailFolderList(mailFolderList, folder.list());
            } else if (type == 3) {
                mailFolderList.add(folder.getFullName());
            }
        }
    }
}
