import type {
	RollTableAuthor,
} from '../rolltable';
import {
	AttributionAuthor,
	reconstituteAttributionAuthorIfExists
} from './AttributionAuthor';
import { Fragment } from 'preact';
import {
	AttributionSet,
	type AttributionSetProps,
	reconstituteAttributionSetIfExists
} from './AttributionSet';
import type { PropsWithChildren } from 'preact/compat';

export interface AttributionPropsFull {
	author: RollTableAuthor|null
	set: AttributionSetProps
}

export interface AttributionPropsEmpty {
	author?: null
	set?: null
}

export type AttributionProps = AttributionPropsFull|AttributionPropsEmpty

export interface PartialAttributionPropsFull {
	author?: Partial<RollTableAuthor>|null
	set?: Partial<AttributionSetProps>
}

export interface PartialAttributionPropsEmpty {
	author?: null
	set?: null
}

export type PartialAttributionProps = PartialAttributionPropsFull|PartialAttributionPropsEmpty

export function reconstituteAttribution(div: HTMLDivElement, partial?: PartialAttributionProps): AttributionProps {
	const set = reconstituteAttributionSetIfExists(
		div.querySelector<HTMLParagraphElement>(".resultSet"),
		partial?.set)
	const author = reconstituteAttributionAuthorIfExists(
		div.querySelector<HTMLParagraphElement>(".author"),
		partial?.author)
	if (!set) {
		return {}
	} else {
		return {
			set: set,
			author: author,
		}
	}
}

export function Attribution({author, set, children}: AttributionProps & PropsWithChildren) {
	return <div class="attribution">
		<div class="attributionBubble">
			{set
				? <Fragment>
					{author && <AttributionAuthor {...author} />}
					<AttributionSet {...set} />
				</Fragment>
				: <p>
					<span>Authorship unknown</span>
				</p>}
			{children}
		</div>
	</div>
}
