use crate::{Connection};
use crate::pop3::pop::Pop;

mod pop;
mod line;

#[derive(Clone)]
pub struct Pop3 {
    pub(crate) connection: Connection,
}

impl Pop3 {
    pub fn new(connection: Connection) -> Self {
        Self {
            connection
        }
    }
    fn connect(&mut self) -> Result<Pop, String> {
        let host = self.connection.host.clone();
        let port = self.connection.port.clone();
        let user_name = self.connection.mail.clone();
        let user_pass = self.connection.pass.clone();

        let conn = Pop::new(host.clone(), port.clone());
        let mut conn = match conn {
            Ok(e) => e,
            Err(e) => {
                return Err(e);
            }
        };
        match conn.login(user_name, user_pass) {
            Ok(_) => {}
            Err(e) => {
                return Err(e);
            }
        };
        Ok(conn)
    }
    /// 获取最大ID
    pub fn mail_id_max(&mut self) -> Result<u32, String> {
        let mut conn = self.connect()?;
        let res = conn.stat()?;
        Ok(res.message_count)
    }
    pub fn mail_id_list(&mut self) -> Result<Vec<String>, String> {
        let mut conn = self.connect()?;
        let res = conn.list()?;
        let mut list = vec![];
        for item in res {
            list.push(item.message_id.to_string());
        }
        Ok(list)
    }
    pub fn mail_id_get(&mut self, mail_id: u32) -> Result<Vec<u8>, String> {
        let mut conn = self.connect()?;
        let res = conn.retr(mail_id)?;
        Ok(res)
    }
    pub fn mail_msg_size(&mut self, mail_id: u32) -> Result<u32, String> {
        let mut conn = self.connect()?;
        let res = conn.msg_size(mail_id)?;
        Ok(res)
    }
}
