use super::session::request;
use scraper::{Html, Selector};
use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct ClassroomCourse {
    name: String,
}

/// Returns all the courses the user is enrolled in
pub async fn get_courses(user_id: i32) -> Result<Vec<ClassroomCourse>, String> {
    let html = request(format!(
        "/main/admin/user_information.php?user_id={}",
        user_id
    ))
    .await?;

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

    // Courses selector
    let courses_selector =
        Selector::parse(".table.table-hover.table-striped.table-bordered.data_table")
            .or_else(|err| Err(format!("Error creating table selector: {:?}", err)))?;
    // tr
    let tr_selector = Selector::parse("tr")
        .or_else(|err| Err(format!("Error creating tr selector: {:?}", err)))?;
    // td
    let td_selector = Selector::parse("td")
        .or_else(|err| Err(format!("Error creating td selector: {:?}", err)))?;

    let table = match fragment.select(&courses_selector).next() {
        Some(t) => t,
        None => {
            // The courses table was not found.
            // If we are in the user page, it means that the user has no courses
            if ensure_is_user_page(&fragment, user_id) {
                return Ok(Vec::new());
            } else {
                // If we are not in the user page, it means that there was an error
                return Err(format!("Error selecting courses table. Not found"));
            }
        }
    };

    let mut courses: Vec<ClassroomCourse> = Vec::new();

    let mut tr_iter = table.select(&tr_selector);
    // Consume table header
    tr_iter.next();

    for table_row in tr_iter {
        let td_els = table_row.select(&td_selector).collect::<Vec<_>>();

        if td_els.len() != 6 {
            return Err(format!(
                "Error parsing tr: td elements count is not 6, but {}",
                td_els.len()
            ));
        }

        let course_name = td_els[1].inner_html();
        courses.push(ClassroomCourse { name: course_name })
    }

    Ok(courses)
}

/// Searches in the document for the user toolbar, and checks if the user id matches
fn ensure_is_user_page(document: &Html, user_id: i32) -> bool {
    // toolbar-user-information

    let user_toolbar = Selector::parse("#toolbar-user-information").unwrap();

    let a_selector = Selector::parse("a").unwrap();

    let toolbar_el = match document.select(&user_toolbar).next() {
        Some(t) => t,
        None => return false,
    };

    let a_element = match toolbar_el.select(&a_selector).next() {
        Some(a) => a,
        None => return false,
    };

    // Get href attribute
    let href_value = a_element.value().attr("href").unwrap_or("");

    // href should be like: https://testing.aulavirtual.eegsac.com/main/mySpace/myStudents.php?student=2142
    let user_id_start = match href_value.find("student=") {
        Some(i) => i + 8,
        None => return false,
    };
    let user_id_str = href_value[user_id_start..].to_string();

    match user_id_str.parse::<i32>() {
        Ok(id) => id == user_id,
        Err(_) => false,
    }
}
