import { useEffect, useState } from '@wordpress/element';
import { select } from '@wordpress/data';
import { RenderGroupBlock } from './render-group';

export const RenderTestimonialSliderBlock = (props) =>{
	
	const { _props, data } = props;
	const { attributes, clientId } = _props;
	const { id, tag } = data;
	const [ preChildCount, setPreChildCount ] = useState(0);
	const [ refreshSlider, setRefreshSlider ] = useState(false);
	
	const hasChildrens = select( 'core/block-editor' ).getBlocks( clientId ).length;
	
	const renderSlider = () =>{
		let jEle = pagelayer_query(`.p-${id}`);
		pagelayer_owl_destroy(jEle, '.pagelayer-testimonials-holder');
		pagelayer_pl_testimonial_slider(jEle);
	}
	
	// For the insert and drag new child
	if(preChildCount != hasChildrens){
		let jEle = pagelayer_query(`.p-${id}`);
		pagelayer_owl_destroy(jEle, '.pagelayer-testimonials-holder');
		setPreChildCount(hasChildrens);
	}
	
	useEffect(() => {
		setTimeout(renderSlider, 200);
	}, [attributes]);
	
	useEffect(renderSlider, [hasChildrens, refreshSlider]);
	
	useEffect(() => {
		var jEle = pagelayer_query(`.p-${id}`);
		
		jEle.find('.pagelayer-owl-carousel').on('refresh.pagelayer.owl', function(){
			setRefreshSlider(!refreshSlider);
		});
		
		if(jEle.find('.pagelayer-testimonials-holder > .pagelayer-owl-stage-outer').length < 1){
			renderSlider();
		}
		
		return (() => {
			jEle.find('.pagelayer-owl-carousel').unbind('refresh.pagelayer.owl');
		});
	});
	
	var elementProps = {
		plTag: tag,
		_props: _props,
	};
		
	return (
		<>
			<RenderGroupBlock className="pagelayer-testimonials-holder pagelayer-owl-holder pagelayer-owl-carousel pagelayer-owl-theme" {...elementProps} />
		</>
	);
}
