import { LabelControl } from './label';
import { MediaUpload } from '@wordpress/block-editor';

export const MediaControl = (props) => {
	
	const { attributes, prop, value, setAttributes} = props;
	const { name } = prop['c'];
	const tmpAtts = attributes?.tmpAtts ?  attributes.tmpAtts : {};
	
	const setURL = pagelayer_empty(tmpAtts[name+'-url']) ? value : tmpAtts[name+'-url'];
	
	var mediaSting = 'Media';
	var allow = [];
	var propType = prop?.type;
	
	if(propType == 'video'){
		allow = ['video'];
		mediaSting = 'Video';
	}else if(propType == 'audio'){
		allow = ['audio'];
		mediaSting = 'Audio';
	}
		
	const handleMediaChange = (e) => {
		const newURL = e.target.value;
		
		const tmp = {
			...tmpAtts,
			[name+'-url']: newURL,
		};
		
		setAttributes({
			[name]: newURL,
			tmpAtts: tmp,
		})
	};

	const onSelectMedia = (videoProps) => {
		const { id, url } = videoProps;
		
		const tmp = {
			...tmpAtts,
			[name+'-url']: url,
		};
		
		setAttributes({
			[name]: id,
			tmpAtts: tmp,
		});
	}
	
	const renderMediaUploader = (open) => {
		return (
			<div className="pagelayer-elp-media-div pagelayer-elp-input-icon">
				<input 
					className="pagelayer-elp-media" 
					name={name}
					type="text"
					value={setURL}				
					placeholder={`Insert ${mediaSting} URL`}				
					onChange={ (e) => handleMediaChange(e) }
					>
				</input>
				<span 
					className="pagelayer-elp-add-media"
					onClick={ () => {open()} }
					title='Open Media Library'
				><i className="pli pli-menu"></i></span>				
			</div>
		);
	}

	return (
		<div className="components-base-control pagelayer-base-control">
			<LabelControl {...props}/>
			<MediaUpload
				title={`Select or Upload ${mediaSting}`}
				onSelect={ onSelectMedia }
				allowedTypes={ allow }
				value={ value }
				render={ ( { open } ) => renderMediaUploader( open ) }
			/>
		</div>
	);	
}