use assetserver::Asset;
use chrono::TimeDelta;
use maud::{DOCTYPE, Markup, PreEscaped, html};
use page::page::{Page, PageMetadata};
use std::pin::Pin;

use crate::{
	components::{
		md::{Markdown, backlinks, meta_from_markdown},
		misc::FarLink,
	},
	routes::assets::{Image_Icon, Styles_Main},
};

mod handouts;
mod index;

pub use handouts::handouts;
pub use index::index;

pub fn links() -> Page {
	/*
	Dead links:

	https://www.commitstrip.com/en/
	http://www.3dprintmath.com/
	*/

	page_from_markdown(include_str!("links.md"), Some(Image_Icon::URL.to_owned()))
}

pub fn betalupi() -> Page {
	page_from_markdown(
		include_str!("betalupi.md"),
		Some(Image_Icon::URL.to_owned()),
	)
}

pub fn htwah_typesetting() -> Page {
	page_from_markdown(
		include_str!("htwah-typesetting.md"),
		Some(Image_Icon::URL.to_owned()),
	)
}

//
// MARK: md
//

fn page_from_markdown(md: impl Into<String>, default_image: Option<String>) -> Page {
	let md: String = md.into();
	let md = Markdown::parse(&md);

	let mut meta = meta_from_markdown(&md)
		.unwrap_or(Some(PageMetadata {
			title: "Invalid frontmatter!".into(),
			..Default::default()
		}))
		.unwrap_or_default();

	if meta.image.is_none() {
		meta.image = default_image
	}

	let html = PreEscaped(md.render());

	Page {
		meta,

		html_ttl: Some(TimeDelta::seconds(60 * 24 * 30)),
		generate_html: Box::new(move |page, ctx| {
			let html = html.clone();

			Box::pin(async move {
				let inner = html! {
					@if let Some(backlinks) = backlinks(page, ctx) {
						(backlinks)
					}

					(html)
				};

				page_wrapper(&page.meta, inner).await
			})
		}),
	}
}

//
// MARK: wrapper
//

pub fn page_wrapper<'a>(
	meta: &'a PageMetadata,
	inner: Markup,
) -> Pin<Box<dyn Future<Output = Markup> + 'a + Send + Sync>> {
	Box::pin(async move {
		html! {
			(DOCTYPE)
			html {
				head {
					meta charset="UTF" {}
					meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" {}
					meta content="text/html; charset=UTF-8" http-equiv="content-type" {}
					meta property="og:type" content="website" {}

					link rel="stylesheet" href=(Styles_Main::URL) {}

					(&meta)
					title { (PreEscaped(meta.title.clone())) }
				}

				body {
					div class="wrapper" {
						main { (inner) }

						footer {
							hr class = "footline" {}
							div class = "footContainer" {
								p {
									"This site was built by hand using "
									(FarLink("https://rust-lang.org", "Rust"))
									", "
									(FarLink("https://maud.lambda.xyz", "Maud"))
									", "
									(FarLink("https://github.com/connorskees/grass", "Grass"))
									", and "
									(FarLink("https://docs.rs/axum/latest/axum", "Axum"))
									"."
								}
							}
						}
					}
				}
			}
		}
	})
}
