use rs_pop3::POP3Result::{POP3List, POP3Stat};
use rs_pop3::POP3Stream;
use openssl::ssl::{SslConnector, SslMethod};
use crate::{Connection};

// mod qq;


#[derive(Clone)]
pub struct Pop3 {
    host: String,
    port: String,

    // name: String,
    mail: String,
    pass: String,

    total_mail: i32,
    total_size: i64,
}

impl Pop3 {
    pub fn new(config: Connection) -> Self {
        Self {

            host: config.host,
            port: config.port,
            // name: config.name,
            mail: config.mail,
            pass: config.pass,
            total_mail: 0,
            total_size: 0,
        }
    }
    fn connect(&mut self) -> POP3Stream {
        println!("连接中... {}", self.host.as_str().clone());
        let mut gmail_socket = match POP3Stream::connect((self.host.as_str().clone(), self.port.parse::<u16>().unwrap()),
                                                         Some(SslConnector::builder(SslMethod::tls()).unwrap().build()),
                                                         self.host.as_str().clone())
        {
            Ok(s) => s,
            Err(e) => {
                println!("失败");
                panic!("{}", e)
            }
        };
        println!("连接成功");
        gmail_socket.login(self.mail.as_str().clone(), self.pass.as_str().clone());
        gmail_socket
    }
    /// 获取总记录数
    pub fn total(&mut self) {
        let mut gmail_socket = self.connect();
        let stat = gmail_socket.stat();
        match stat {
            POP3Stat { num_email, mailbox_size } => {
                self.total_mail = num_email;
                self.total_size = mailbox_size;
                println!("总邮件数量: {},  mailbox_size:{}", self.total_mail, self.total_size)
            }
            _ => println!("Err for stat"),
        }
        gmail_socket.quit();
    }
    pub fn list(&mut self) {
        let mut conn = self.connect();
        let list_all = conn.list(None);
        match list_all {
            POP3List { emails_metadata } => {
                for i in emails_metadata.iter() {
                    println!("message_id: {},  message_size: {}", i.message_id, i.message_size);
                }
            }
            _ => println!("Err for list_all"),
        }
        conn.quit();
    }

    // fn save_file(&mut self, message_id: i32, data: Vec<String>) {
    //     let text = data.join("");
    //     let filename = format!("/Users/carry/carryxdcoding/helpers/br-email/examples/file/message_{}", message_id);
    //     fs::write(filename, text).unwrap();
    // }
}