use core::panic;
use std::io::{Bytes, Read};
use iced::widget::image::Handle;
use rss::{Channel};
use reqwest::{self, blocking::Client, header::USER_AGENT};

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(e) => { 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(e) => {
            println!("Failed to download image.");
            None
        }
    }
}