<script module lang="ts">
	import { tagImg } from "./tag_store/TagImgHelper.svelte";
	import "./postHelpers.scss";

	let posts = import.meta.glob("/src/routes/posts/**/*.md", {
		eager: true,
	});
	export type Post = {
		title: string;
		description: string;
		path?: string;
		catagory: string;
		date: Date;
		updated?: Date;
		tags: string[];
	};
	export { PostCard, PostHeader };
	function dateRender(date: Date): string {
		const day = String(date.getDate()).padStart(2, "0");
		const month = String(date.getMonth() + 1).padStart(2, "0"); // Months are zero-indexed
		const year = String(date.getFullYear()).slice(-2); // Get last two digits of the year

		return `${day}/${month}/${year}`;
	}
	export function getPosts(): Post[] {
		let postsNew: Post[] = new Array();
		Object.entries(posts).map(([path, module]) => {
			const metadata = module.metadata;
			let date = new Date(metadata.date);
			let updated = new Date(metadata.updated);
			let tags = metadata.tags.split(" ");
			let trimedPath = path.replace("/src/routes/", "");
			let trimmedPath = trimedPath.replace("/+page.md", "");
			let post: Post = {
				title: metadata.title,
				description: metadata.description,
				date: date,
				path: trimmedPath,
				updated: updated,
				catagory: metadata.catagory,
				tags: tags,
			};
			postsNew.push(post);
		});
		return postsNew;
	}
	/// Doesn't provide path
	export function postFromProps(props: any): Post {
		const metadata = props;
		let date = new Date(metadata.date);
		let updated = new Date(metadata.updated);
		let tags = metadata.tags.split(" ");
		// let trimedPath = path.replace("/src/routes/", "");
		// let trimmedPath = trimedPath.replace("/+page.md", "");
		let post: Post = {
			title: metadata.title,
			description: metadata.description,
			date: date,
			updated: updated,
			catagory: metadata.catagory,
			tags: tags,
		};
		return post;
	}
</script>

{#snippet PostCard(post: Post)}
	<a class="container" href="/{post.path}">
		<div class="card">
			<div class="left">
				<span class="post-title">{post.title}</span>
				<div class="seperater"></div>
				<p class="post-descr">{post.description}</p>
				<div class="seperater"></div>
			</div>
			<div class="right">
				<div class="icons">
					<div class="icon_container">
						{@render tagImg(post.tags[0])}
					</div>
					<div class="icon_container">
						{@render tagImg(post.tags[1])}
					</div>
					<div class="icon_container">
						{@render tagImg(post.tags[2])}
					</div>
				</div>
				<div class="seperater"></div>
				<span title={post.date.toString()}>{dateRender(post.date)}</span>
			</div>
		</div>
	</a>
{/snippet}

{#snippet PostHeader(post: Post)}
	<div class="card-header-top-div">
		<div class="card-header-container">
			<div class="card-header-container-left">
				<span class="card-header-title">{post.title}</span>
				<span class="card-header-descr">{post.description}</span>
			</div>
			<div class="card-header-container-right"></div>
		</div>
	</div>
{/snippet}
