/**
 * List class colles from BJColle (list ID and secret).
 * URL: https://bjcolle.fr/students_dashboard_class.php
 */
use reqwest::{self, Client};
use scraper::{Html, Selector};
use std::collections::HashMap;
use url::Url;

use crate::parser::utils::hash_text;

pub async fn fetch(
    session: &str,
    date: Option<&str>,
    last_hash: &str,
) -> Result<(Vec<(String, String, String)>, String), Box<dyn std::error::Error>> {
    let mut url = String::from("https://bjcolle.fr/students_dashboard_class.php?erasedate=1");
    if let Some(date) = date {
        url = format!(
            "https://bjcolle.fr/students_dashboard_class.php?go={}",
            date
        );
    }

    // Retrieve page content
    let response = Client::new()
        .get(url)
        .header("Cookie", session)
        .send()
        .await?
        .text()
        .await?;

    // Calculate the hash of the response
    let hash = hash_text(&response);
    if hash == last_hash {
        return Ok((Vec::new(), hash));
    }

    let document = Html::parse_document(&response);

    // Select the table rows containing colles
    let row_selector = Selector::parse("#Choix > a.bouton_eleve2").unwrap();

    let mut colles = Vec::new();

    for row in document.select(&row_selector) {
        // Extract ID and secret from each row
        if let Some(href) = row.value().attr("href") {
            if let Some((colle_id, colle_secret)) = parse_colle_info(href) {
                let rows: Vec<&str> = row.text().collect();
                let examiner_name = rows[2].trim().to_string();
                colles.push((colle_id, colle_secret, examiner_name));
            } else {
                eprintln!("Failed to parse colle info from URL: {}", href);
            }
        } else {
            eprintln!("Row does not contain a valid href attribute.");
        }
    }

    Ok((colles, hash))
}

fn parse_colle_info(raw_url: &str) -> Option<(String, String)> {
    let full_url = format!("https://dummy.host/{}", raw_url); // must be absolute
    let parsed = Url::parse(&full_url).ok()?;

    let query: HashMap<_, _> = parsed.query_pairs().into_owned().collect();

    let colle_id = query.get("colle")?.to_string();
    let colle_secret = query.get("hgfebrgl8ri3h")?.to_string();

    Some((colle_id, colle_secret))
}
