import React from 'react';
import { createNewImage, getWaterMarkContent, getWaterMarkUseState } from './utils';
import { useMemo, useEffect, useRef, useState } from 'react';
import waterMakeDomStore from './waterMakeDom.store'
import { observer, useLocalStore } from 'mobx-react';


const WaterMakeDom = (props) => {
	const { className = '', waterMakeRule, waterSwitch, imgType } = props;
	const [currentRule, setCurrentRule] = useState()
	const [currentSwitch, setCurrentswitch] = useState()
	const playerRef = useRef(null)
	const store = useLocalStore(() => waterMakeDomStore)

	const markerPath = useMemo(() => {
		if (!currentRule) return ''

		const contents = getWaterMarkContent(currentRule)
		if (!contents.length) return ''
		const canvas = createNewImage({
			contents,
			fontSize: Math.min(30, Math.max(10, currentRule.fontSize || 0)),
			density: currentRule.showLevel ?? 1,
			opacity: currentRule?.transparency ?? 100
		})
		return canvas.toDataURL('image/png')
	}, [currentRule])

	useEffect(() => {
		if (!waterMakeRule && imgType) {
			store.loadState()
		}
	}, [waterMakeRule, imgType])

	useEffect(() => {
		if (!waterMakeRule && imgType) {
			setCurrentRule(store.state.rules.find(o => o.imgType === imgType))
			setCurrentswitch(store.state.isCompulsory)
		} else {
			setCurrentRule(waterMakeRule)
			setCurrentswitch(waterSwitch)
		}
	}, [store.state.rules, store.state.isCompulsory, waterMakeRule, imgType, waterSwitch])

	return (
		<div
			className={"player-marke" || className}
			ref={playerRef}
			style={{
				position: 'absolute',
				left: 0,
				top: 0,
				width: '100%',
				height: '100%',
				zIndex: 1,
				background: currentRule && currentSwitch && getWaterMarkUseState(currentRule, currentSwitch) ? `url(${markerPath})` : "transparent",
				// backgroundSize: "100% 100%"
			}}
		/>
	)
}
WaterMakeDom.store = waterMakeDomStore
WaterMakeDom.utils = { createNewImage, getWaterMarkContent, getWaterMarkUseState }
export default observer(WaterMakeDom);
