use xml_builder::{XMLBuilder, XMLElement, XMLVersion};

pub fn generate(
    config: crate::config::Syndication,
    post_index: &Vec<crate::index::BlogPost>,
) -> String {
    let mut xml = XMLBuilder::new()
        .version(XMLVersion::XML1_1)
        .encoding("UTF-8".into())
        .build();

    let mut feed = XMLElement::new("feed");
    feed.add_attribute("xmlns", "http://www.w3.org/2005/Atom");

    let mut id = XMLElement::new("id");
    id.add_text(config.link).unwrap();
    feed.add_child(id).unwrap();

    let mut title = XMLElement::new("title");
    title.add_text(config.title).unwrap();
    feed.add_child(title).unwrap();

    let mut updated = XMLElement::new("updated");
    let last_update = chrono::DateTime::from_timestamp(last_update(post_index), 0).unwrap();
    updated.add_text(last_update.to_rfc3339()).unwrap();
    feed.add_child(updated).unwrap();

    if config.subtitle.is_some() {
        let mut subtitle = XMLElement::new("subtitle");
        subtitle.add_text(config.subtitle.unwrap()).unwrap();
        feed.add_child(subtitle).unwrap();
    }

    if config.icon.is_some() {
        let mut icon = XMLElement::new("icon");
        icon.add_text(config.icon.unwrap()).unwrap();
        feed.add_child(icon).unwrap();
    }

    xml.set_root_element(feed);
    let mut writer: Vec<u8> = Vec::new();
    xml.generate(&mut writer).unwrap();

    let mut output_xml = String::new();

    for e in writer {
        output_xml += &e.as_ascii().unwrap().to_string();
    }

    output_xml
}

fn last_update(post_index: &Vec<crate::index::BlogPost>) -> i64 {
    let mut last_timestamp: i64 = i64::MIN;

    for post in post_index {
        if post.sort_date > last_timestamp {
            last_timestamp = post.sort_date;
        }
    }
    last_timestamp
}