import type { RollTableAuthor } from '../rolltable';

export function reconstituteAttributionAuthorIfExists(element: HTMLParagraphElement | null, partial?: Partial<RollTableAuthor>|null): RollTableAuthor|null {
	if (!element || partial === null) {
		return null
	}
	return reconstituteAttributionAuthor(element, partial)
}

export function reconstituteAttributionAuthor(p: HTMLParagraphElement, partial?: Partial<RollTableAuthor>): RollTableAuthor {
	return {
		id: partial?.id ?? parseInt(p.dataset.id!!),
		name: partial?.name ?? p.querySelector<HTMLElement>(".authorName")!.innerText,
		url: typeof partial?.url !== "undefined" ? partial.url : (p.querySelector<HTMLAnchorElement>(".authorUrl")?.href ?? null),
		relation: partial?.relation ?? p.querySelector<HTMLElement>(".authorRelation")!.innerText,
	}
}

export function AttributionAuthor({ relation, id, url, name }: RollTableAuthor) {
	return <p class="author" data-id={id}>
		<span class="authorRelation">{relation}</span>
		{" "}
		<span class="authorName">{url
			? <a class="authorUrl" href={url} rel="external nofollow noreferrer">{name}</a>
			: name
		}</span>
	</p>
}
