use imap::ClientBuilder;
use crate::{Connection};


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

impl Imap {
    pub fn new(connection: Connection) -> Self {
        Self {
            connection,
        }
    }
    /// 获取最大ID
    pub fn mail_id_max(&mut self) -> Result<u32, String> {
        let host = self.connection.host.as_str().clone();
        let port = self.connection.port.parse::<u16>().unwrap().clone();
        let user_name = self.connection.mail.as_str().clone();
        let user_pass = self.connection.pass.as_str().clone();


        let client = match ClientBuilder::new(host.clone(), port.clone()).connect() {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("连接 失败: {}", e.to_string()));
            }
        };
        let mut conn = match client.login(user_name.clone(), user_pass.clone()).map_err(|e| e.0) {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("登陆失败 {}", e.to_string()));
            }
        };

        return match conn.select("INBOX") {
            Ok(e) => {
                conn.logout().unwrap();
                Ok(e.exists)
            }
            Err(e) => {
                Err(e.to_string())
            }
        };
    }

    pub fn mail_id_list(&mut self) -> Result<Vec<String>, String> {
        let host = self.connection.host.as_str().clone();
        let port = self.connection.port.parse::<u16>().unwrap().clone();
        let user_name = self.connection.mail.as_str().clone();
        let user_pass = self.connection.pass.as_str().clone();

        let client = match ClientBuilder::new(host.clone(), port.clone()).connect() {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("连接 失败: {}", e.to_string()));
            }
        };
        let mut conn = match client.login(user_name.clone(), user_pass.clone()).map_err(|e| e.0) {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("登陆失败 {}", e.to_string()));
            }
        };

        match conn.select("INBOX") {
            Ok(e) => e,
            Err(e) => {
                return Err(e.to_string());
            }
        };
        let messages = conn.search("ALL").unwrap();
        let mut list = vec![];
        for message in messages {
            list.push(message.to_string().as_str().parse::<u32>().unwrap().clone());
        }
        list.sort();
        let list = list.iter().map(|x| x.to_string()).collect();
        Ok(list)
    }


    pub fn mail_id_get(&mut self, mail_id: u32) -> Result<Vec<u8>, String> {
        let host = self.connection.host.as_str().clone();
        let port = self.connection.port.parse::<u16>().unwrap().clone();
        let user_name = self.connection.mail.as_str().clone();
        let user_pass = self.connection.pass.as_str().clone();

        let client = match imap::ClientBuilder::new(host.clone(), port.clone()).connect() {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("连接 失败: {}", e.to_string()));
            }
        };
        let mut conn = match client.login(user_name.clone(), user_pass.clone()).map_err(|e| e.0) {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("登陆失败 {}", e.to_string()));
            }
        };
        match conn.select("INBOX") {
            Ok(_) => {}
            Err(e) => {
                return Err(e.to_string());
            }
        };
        let messages = match conn.fetch(mail_id.to_string().as_str().clone(), "RFC822") {
            Ok(messages) => messages,
            Err(e) => {
                return Err(format!("fetch: {}", e.to_string()));
            }
        };
        let message = if let Some(m) = messages.iter().next() {
            m
        } else {
            return Err(format!("message: 错误"));
        };
        let body = match message
            .body()
            .map(|body|
                {
                    body.to_vec()
                }
            ) {
            None => {
                vec![]
            }
            Some(e) => {
                e
            }
        };

        conn.logout().unwrap();
        Ok(body)
    }

    pub fn mail_msg_size(&mut self, mail_id: u32) -> Result<u32, String> {
        let host = self.connection.host.as_str().clone();
        let port = self.connection.port.parse::<u16>().unwrap().clone();
        let user_name = self.connection.mail.as_str().clone();
        let user_pass = self.connection.pass.as_str().clone();

        let client = match ClientBuilder::new(host.clone(), port.clone()).connect() {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("连接 失败: {}", e.to_string()));
            }
        };
        let mut conn = match client.login(user_name.clone(), user_pass.clone()).map_err(|e| e.0) {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("登陆失败 {}", e.to_string()));
            }
        };
        match conn.select("INBOX") {
            Ok(_) => {}
            Err(e) => {
                return Err(e.to_string());
            }
        };

        let messages = match conn.fetch(mail_id.to_string().as_str().clone(), "ALL") {
            Ok(messages) => messages,
            Err(e) => {
                return Err(format!("fetch: {}", e.to_string()));
            }
        };
        let message = if let Some(m) = messages.iter().next() {
            m
        } else {
            return Err(format!("message: 错误"));
        };
        conn.logout().unwrap();
        Ok(message.size.unwrap())
    }

    pub fn mail_msg_uidl(&mut self, mail_id: u32) -> Result<String, String> {
        let host = self.connection.host.as_str().clone();
        let port = self.connection.port.parse::<u16>().unwrap().clone();
        let user_name = self.connection.mail.as_str().clone();
        let user_pass = self.connection.pass.as_str().clone();

        let client = match ClientBuilder::new(host.clone(), port.clone()).connect() {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("连接 失败: {}", e.to_string()));
            }
        };
        let mut conn = match client.login(user_name.clone(), user_pass.clone()).map_err(|e| e.0) {
            Ok(e) => e,
            Err(e) => {
                return Err(format!("登陆失败 {}", e.to_string()));
            }
        };
        match conn.select("INBOX") {
            Ok(_) => {}
            Err(e) => {
                return Err(e.to_string());
            }
        };

        let messages = match conn.fetch(mail_id.to_string().as_str().clone(), "UID") {
            Ok(messages) => messages,
            Err(e) => {
                return Err(format!("fetch: {}", e.to_string()));
            }
        };
        let message = if let Some(m) = messages.iter().next() {
            m
        } else {
            return Err(format!("message: 错误"));
        };
        conn.logout().unwrap();
        Ok(message.uid.unwrap().to_string())
    }
}
