// 2d分子结构图
import { useCallback, useEffect } from "react";
import { Box } from "@mui/material";
import { useMessage } from "@/components/MySnackbar";
var Kekule = require("kekule").Kekule;

type IKekuleViewProps = {
	id: string;
	width?: string;
	height?: string;
	smi: string;
	backgroundColor?: string;
	style?: any;
	onClick?: any;
	toolbar?: boolean;
};

declare global {
	interface Window {
		RDKit: any;
	}
}

const KekuleView = (props: IKekuleViewProps) => {
	const {
		id,
		width = "100%",
		height = "100%",
		smi = "",
		backgroundColor = "#fff",
		style = {},
		onClick,
		toolbar = false,
	} = props;
	const Message = useMessage();

	const rander = useCallback(() => {
		if (smi) {
			try {
				let molecule = Kekule.IO.loadFormatData(
					window.RDKit.get_mol(smi).get_kekule_form(),
					"mol"
				);
				const contentBox = document.getElementById(id);
				if (contentBox) {
					contentBox.innerHTML = "";
				}
				let chemViewer = new Kekule.ChemWidget.Viewer(document);
				chemViewer.setDimension(width, height);
				chemViewer.setBackgroundColor(backgroundColor);
				chemViewer
					.appendToElem(document.getElementById(id))
					.setChemObj(molecule);
				chemViewer.setEnableToolbar(toolbar);
				chemViewer.setAutofit(true);
				chemViewer.setPadding(26);
				chemViewer.setEnableDirectInteraction(false);
			} catch (err) {
				console.log(err);
				Message.error("分子结构图渲染失败，请刷新重试。");
			}
		}
	}, [smi, Message, id, height, width, backgroundColor, toolbar]);

	useEffect(() => {
		rander();
	}, [rander]);

	window.onresize = () => {
		rander();
	};

	return (
		<Box
			id={id}
			sx={{
				cursor: onClick ? "pointer" : "unset",
				width: "99%",
				height: "99%",
				...style,
			}}
			onClick={onClick}
		></Box>
	);
};

export default KekuleView;
