import Placeholder from "react-bootstrap/Placeholder";
import React from "react";
import Stack from "react-bootstrap/Stack";

import Client from "./client/Client";
import { IAccount, IEmail } from "./client/types";

type EmailContentProps = {
	account: IAccount | null;
	client: Client | null;
	email: IEmail | null;
	emailId: string;
};

type EmailContentState = {};

class EmailContent extends React.Component<
	EmailContentProps,
	EmailContentState
> {
	componentDidMount() {
		this.ensureData();
	}
	componentDidUpdate() {
		this.ensureData();
	}

	ensureData() {
		if (this.props.account == null) return;
		if (this.props.client == null) return;
		this.props.client.ensureEmailContent(
			this.props.account.id,
			this.props.emailId,
		);
	}

	render() {
		const email = this.props.email;
		if (email == null || email.bodyValues == null) {
			return <Placeholder />;
		} else if (email.textBody != null) {
			return (
				<Stack>
					<li>{email.receivedAt}</li>
					{email.textBody.map((t) =>
						t.partId === undefined ? (
							<Placeholder />
						) : (
							<div
								dangerouslySetInnerHTML={{
									__html: email.bodyValues![t.partId].value,
								}}
							/>
						),
					)}
				</Stack>
			);
		} else if (email.htmlBody != null) {
			return (
				<Stack>
					{email.htmlBody.map((h) =>
						h.partId === undefined ? (
							<Placeholder />
						) : (
							<div
								dangerouslySetInnerHTML={{
									__html: email.bodyValues![h.partId].value,
								}}
							/>
						),
					)}
				</Stack>
			);
		} else {
			return <p>Nothing to display :/</p>;
		}
	}
}
export default EmailContent;
