use core::panic;
use iced::widget::image::Handle;
use rss::{Channel};
use reqwest::{self, blocking::Client, header::USER_AGENT};
use scraper::{Html, Selector};

fn get_content(url: &str) -> Option<String> {
    let client = Client::new();
    let res = client.get(url)
    .header(USER_AGENT,"RSS Reader")
    .send();
    match res {
        Ok(resp) => {
            match resp.text() {
                Ok(body) => {return Some(body)}
                Err(_) => {return None}
            }
        }
        Err(_) => {return None}
    }
}

pub fn get_feeds(url: &str) -> Option<Vec<Channel>>{
    let page = get_content(url).unwrap();
    let doc = Html::parse_document(&page);
    let link_selector = Selector::parse("head link").unwrap();
    let mut feeds: Vec<Channel> = Vec::new();
    for e in doc.select(&link_selector) {
        if let Some(rel) = e.value().attr("rel") {
            if rel == "alternate" {
                if let Some(href) = e.value().attr("href") {
                    match load_rss(href) {
                        Some(c) => {feeds.push(c)}
                        None => {}
                    }
                }
            }
        }
    }
    return match feeds.len() {
        0 => None,
        _ => {Some(feeds)}
    }
}

pub fn is_feed(url: &str) -> bool {
    match get_feeds(url) {
        Some(_) => true,
        None => false
    }
}

pub fn load_rss(url: &str) -> Option<Channel>{
    let client = Client::new();
    let res = client.get(url)
    .header(USER_AGENT,"RSS Reader")
    .send();
    match res {
        Ok(resp) => {
            match resp.bytes() {
                Ok(body) => {
                    match Channel::read_from(&*body) {
                        Ok(channel) => {Some(channel)}
                        Err(e) => {panic!("Error parsing feed:\n{}",e);}
                    }


                },
                Err(_) => { panic!("Empty response")}
            }
        },
        Err(err) => {panic!("Error loading feed.:{}",err)}
    }
} 
pub fn get_item_image(item: &rss::Item) -> Option<&str> {
    // Only bother with itunes:image
    print!("{} \n", item.title().unwrap());
    match item.itunes_ext() {
        Some(e) => match e.image() {
            Some(img) => {
                println!("Image found: {}", img);
                Some(img)
            }
            None => {
                println!("Itunes extension found, but image was not..");
                None
            }
        },
        None => {
            println!("found no extensions");
            None
        }
    }
}
pub fn download_image(url: &str) -> Option<iced::widget::image::Handle>{
    match reqwest::blocking::get(url) {
        Ok(r) => {
            let img: Handle = Handle::from_bytes(r.bytes().unwrap());
            Some(img)
        }
        Err(_) => {
            println!("Failed to download image.");
            None
        }
    }
}
