use scraper::{Html, Selector};

use super::session::request;

/// Gets the expiration date of the user with the given id, in format "YYYY-MM-DD HH:MM"
pub async fn get_expiration_date(user_id: i32) -> Result<String, String> {
    let html = request(format!("/main/admin/user_edit.php?user_id={}", user_id)).await?;

    let fragment = Html::parse_document(&html);

    let date_selector = Selector::parse("#expiration_date_alt")
        .or_else(|err| Err(format!("Error creating date selector: {:?}", err)))?;

    let input_el = match fragment.select(&date_selector).next() {
        Some(el) => el,
        None => return Err(format!("#expiration_date_alt not found")),
    };

    match input_el.value().attr("value") {
        Some(date) => Ok(String::from(date)),
        None => return Err(format!("value attribute not found in #expiration_date_alt")),
    }
}
