use once_cell::sync::Lazy;
use regex::Regex;
use std::fmt::Write;

static COMPRESS_NEWLINES: Lazy<Regex> = Lazy::new(|| Regex::new(r"[\n]{2,}").expect("Failed to create RegEx"));

pub struct Text2Html;

impl Text2Html {
    pub fn process(text: &str) -> String {
        let text = COMPRESS_NEWLINES.replace_all(text, "\n\n");
        text.split("\n\n")
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .fold(String::new(), |mut output, s| {
                let _ = writeln!(output, "<p>{}</p>", s.replace('\n', "<br>\n"));
                output
            })
    }
}

#[cfg(test)]
mod tests {
    use super::Text2Html;
    use test_log::test;

    #[test]
    pub fn youtube() {
        let article = r#"
Check Out Overview of PBS Terra: https://bit.ly/33otrUn



If you rank the most habitable places in our solar system Venus lands pretty low, with surface temperatures hot enough to melt lead and sulphuric acid rain. And yet it may have just jumped to the front of the pack. In fact, we may have detected the signature of alien life - Venusian life -for the first time.



Sign Up on Patreon to get access to the Space Time Discord! 
https://www.patreon.com/pbsspacetime

Check out the Space Time Merch Store
https://pbsspacetime.com/

Sign up for the mailing list to get episode notifications and hear special announcements!
https://tinyurl.com/yx9cusk5

Hosted by Matt O'Dowd
Written by Matt O'Dowd
Graphics by Leonardo Scholzer, Yago Ballarini, & Pedro Osinski
Directed by: Andrew Kornhaber
Camera Operator: Setare Gholipour
Executive Producers: Eric Brown & Andrew Kornhaber

Special Thanks to All our Supporters on Patreon!

Big Bang
Brodie Rao
Scott Gray
Robert Doxtator
Ahmad Jodeh
Caed Aldwych
Radu Negulescu
Alexander Tamas
Morgan Hough
Juan Benet
Fabrice Eap
Mark Rosenthal
David Nicklas

Quasar
Alec S-L
Christina Oegren
Mark Heising
Vinnie Falco

Hypernova
Lucas Morgan
William Bryan
Mark Matthew Bosko
Justin Jermyn
Jason Finn
Антон Кочков
Julian Tyacke
Syed Ansar
John R. Slavik
Mathew
Danton Spivey
Donal Botkin
John Pollock
Edmund Fokschaner
Joseph Salomone
Matthew O'Connor
Chuck Zegar
Jordan Young
Hank S
John Hofmann
Timothy McCulloch

Gamma Ray Burst
Sean Warniaha
Tonyface
John Robinson
A G
Kevin Lee
Adrian Hatch
Yurii Konovaliuk
John Funai
Cass Costello
Geoffrey Short
Bradley Jenkins
Kyle Hofer
Tim Stephani
Luaan
AlecZero
Malte Ubl
Nick Virtue
Scott Gossett
David Bethala
Dan Warren
Patrick Sutton
John Griffith
Daniel Lyons
Josh Thomas
DFaulk
Kevin Warne
Andreas Nautsch
Brandon labonte
Lucas Morgan
"#;

        let html = Text2Html::process(article);
        let needle = "<p>Check Out Overview of PBS Terra: https://bit.ly/33otrUn</p>";
        assert_eq!(needle, &html[..needle.len()]);
    }
}
