import {
	Attribution,
	type AttributionPropsEmpty, type AttributionPropsFull,
	type PartialAttributionProps, type PartialAttributionPropsEmpty,
	reconstituteAttribution,
} from './Attribution';
import {
	reconstituteResultText,
	ResultText,
	type ResultTextPropsFull,
	type ResultTextPropsLimited
} from './ResultText';
import { LinkButton } from './Button';
import { responseIdPrefix } from './ResponseElement';
import { IncludesResponses } from './ResponsesPage';
import { useContext } from 'preact/hooks';

export type GeneratedResultPropsFull = AttributionPropsFull & ResultTextPropsFull

export type GeneratedResultPropsLimited = AttributionPropsEmpty & ResultTextPropsLimited

export type GeneratedResultProps = GeneratedResultPropsFull|GeneratedResultPropsLimited


export type PartialGeneratedResultPropsFull = PartialAttributionProps & Partial<ResultTextPropsFull>

export type PartialGeneratedResultPropsLimited = PartialAttributionPropsEmpty & Partial<ResultTextPropsLimited>

export type PartialGeneratedResultProps = PartialGeneratedResultPropsFull|PartialGeneratedResultPropsLimited

export function reconstituteGeneratedResult(div: HTMLDivElement, partial?: PartialGeneratedResultProps): GeneratedResultProps {
	const result =
		reconstituteResultText(div.querySelector(".resultText")!, partial)
	const attribution =
		reconstituteAttribution(div.querySelector(".attribution")!, partial)
	if (result.updated && attribution.set) {
		return {
			...attribution,
			...result,
		}
	} else {
		return {
			...result as ResultTextPropsLimited,
		}
	}
}

export function GeneratedResult(props: GeneratedResultProps) {
	const includesResponses = useContext(IncludesResponses);
	return <div class="generatedResult attributed">
		<ResultText {...props} />
		<Attribution {...props}>
			{includesResponses && props.set
				? <p><LinkButton class={"jumpToResponse"} href={`#${responseIdPrefix}${props.mappingId}`}>Jump to Result in List</LinkButton></p>
				: null}
		</Attribution>
	</div>
}
