import { useState } from '@wordpress/element';
import { LabelControl } from './label';

export const SelectControl = (props) =>{
	
	const { prop, label, value, setAttributes, attributes } = props;
	const { name } = prop['c'];
	
	const handleSelectChange = (e) => {
		var val = e.target.value;

		setAttributes({ [name]: val });

		if( name == 'animation' ){
			var jEle = jQuery(`.p-${attributes['pagelayer-id']}`);
			var sel = jQuery(e.target);
			pagelayer_trigger_anim(jEle, sel, val);
		}
	};
	
	const renderOptions = () => {
		return Object.keys(prop.list).map((groupOrValue, index) => {
			if (typeof prop.list[groupOrValue] === 'string') {
				return (
					<option
						key={index}
						value={groupOrValue}
						selected={groupOrValue == value ? 'selected' : ''}
					>
					{prop.list[groupOrValue]}
					</option>
				);
			}else{
				return (
					<optgroup key={index} label={groupOrValue}>
						{Object.keys(prop.list[groupOrValue]).map((subOption, subIndex) => (
						<option
							key={subIndex}
							value={subOption}
							selected={subOption == value ? 'selected' : ''}
						>
						{prop.list[groupOrValue][subOption]}
						</option>
						))}
					</optgroup>
				);
			}
		});
	};
	
	return (
		<div className="components-base-control pagelayer-base-control pagelayer-flex">
			<LabelControl {...props}/>
			<div className="pagelayer-elp-select-div pagelayer-elp-pos-rel">
				<select
					className="pagelayer-elp-select pagelayer-select"
					name={name}
					onChange={handleSelectChange}
				>
				{renderOptions()}
				</select>
			</div>
		</div>
	);	
}

const pagelayer_trigger_anim = (elem, sel, anim) => {

	var classList = elem.attr('class');
	classList = classList.split(/\s+/);

	jQuery(sel).find('option').each(function(){
		var found = jQuery.inArray( jQuery(this).val(), classList );
		if( found != -1){
			elem.removeClass(jQuery(this).val());
		}
	});
	
	elem.css('animation-name', '');
	elem.removeClass('pagelayer-wow').addClass(anim + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
		jQuery(this).removeClass(anim+ ' animated');
	});
}