   /**
 * External dependencies
 */
import classnames from 'classnames';

/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/packages/packages-i18n/
 */
import { __ } from "@wordpress/i18n";

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/packages/packages-block-editor/#useBlockProps
 */
import { useBlockProps, InspectorControls, MediaPlaceholder, MediaReplaceFlow, BlockControls, BlockIcon, AlignmentToolbar, RichText} from "@wordpress/block-editor";

import { PanelBody, Button, RangeControl } from '@wordpress/components';

import { video as icon } from '@wordpress/icons';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import "./editor.scss";

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/#edit
 *
 * @return {WPElement} Element to render.
 */

const ALLOWED_MEDIA_TYPES = [ 'video' ];
export default function Edit(props) {

	const { attributes, setAttributes, className} = props;

	const {mediaId, mediaUrl, content, iconSize, alignment, style} = attributes;

	setAttributes({style: props.attributes.className});

	const domain_from_url = (mediaUrl) => {
		var result, match, mediaId, domain, error;
		if (match = mediaUrl.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n\?\=]+)/im)) {
			result = match[1];
			if (match = result.match(/^[^\.]+\.(.+\..+)$/)) {
				result = match[1];
			}
			domain = result;
		}
	
		if( 'youtube.com' === domain ) {
			var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
			match = mediaUrl.match(regExp);
			if (match && 11 == match[7].length ) {
				mediaId = match[7];
			}
			
		} else if ( 'vimeo.com' === domain ) {
			var regExp = /^.*((vimeo.com\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
			match = mediaUrl.match(regExp);
			if (match ) {
				mediaId = match[7];
			}
		} else {
			mediaId = '';
			mediaUrl = '';
			domain = '';
			error = 'Invalid Link';
		}
		return {
			mediaId, mediaUrl, domain, error
		}
	}


	const removeMedia = () => {
		setAttributes({
			mediaId: '',
			mediaUrl: '',
			domain: ''
		});
	}

	const classes = classnames( className, {
		'is-transient': true,
	} );

	const blockProps = useBlockProps( {
		className: classes,
	} );

	const onSelectVideo = (video) => {
		setAttributes({
			mediaId: video.id,
			mediaUrl: video.url,
			domain: ''
		});
	}
	const onSelectURL = (url) => {
		
		let res = domain_from_url(url);
		const {mediaId, mediaUrl, domain, error} = res;
		if( undefined !== error ) {
			alert(error);
			return false;
		}
		setAttributes({
			mediaId, mediaUrl, domain
		});
	}
	const onUploadError = () => {

	}
	const noticeUI = () => {

	}

	const onChangeAlignment = ( newAlignment ) => {
		setAttributes( {
			alignment: newAlignment === undefined ? 'none' : newAlignment,
		} );
	};

	const onChangeContent = ( content ) => {
		setAttributes( {content} );
	};

	return (
		<>
			<div { ...blockProps }>
				<BlockControls>
					<AlignmentToolbar
						value={ attributes.alignment }
						onChange={ onChangeAlignment }
					/>
				</BlockControls>
				<BlockControls group="other">
					<MediaReplaceFlow
						mediaId={ mediaId }
						mediaURL={ mediaUrl }
						allowedTypes={ ALLOWED_MEDIA_TYPES }
						accept="video/*"
						onSelect={ onSelectVideo }
						onSelectURL={ onSelectURL }
						onError={ onUploadError }
					/>
				</BlockControls>
				<InspectorControls>
					<PanelBody
						title={__('Pop Video Options', 'awp')}
						initialOpen={ true }
					>
						<RangeControl
							label="Icon Size"
							value={ iconSize }
							onChange={ ( value ) => setAttributes({iconSize: value}) }
							min={ 50 }
							max={ 100 }
						/>
					</PanelBody>
					</InspectorControls>
				{ ! mediaUrl && (
				<MediaPlaceholder
					icon={ <BlockIcon icon={ icon } /> }
					onSelect={ onSelectVideo }
					onSelectURL={ onSelectURL }
					accept="video/*"
					allowedTypes={ ALLOWED_MEDIA_TYPES }
					value={ attributes }
					notices={ noticeUI }
					onError={ onUploadError }
				/>) }
				{mediaUrl && (
					<>
					<div className={`content ${alignment}`}>
						<a id="myBtn" href="javascript:void(0)" className={`video-play`}>
							{
								('is-style-alt' === props.attributes.className) ? 
								<svg width={iconSize} height={iconSize} className="icon-play-alt" viewBox="0 0 1200 1200">
									<path d="M600,1200C268.6,1200,0,931.3,0,600S268.6,0,600,0  s600,268.6,600,600S931.3,1200,600,1200z M450,300.4v599.1L900,600L450,300.4z"/>
								</svg>
							 : 
							 <svg width={iconSize} height={iconSize} className="icon-play" viewBox="0 0 485 485">
								<g>
									<path d="M414,71C368.2,25.2,307.3,0,242.5,0S116.8,25.2,71,71C25.2,116.8,0,177.7,0,242.5S25.2,368.2,71,414   c45.8,45.8,106.7,71,171.5,71s125.7-25.2,171.5-71c45.8-45.8,71-106.7,71-171.5S459.8,116.8,414,71z M242.5,455   C125.3,455,30,359.7,30,242.5S125.3,30,242.5,30S455,125.3,455,242.5S359.7,455,242.5,455z"/>
									<polygon points="181.1,336.6 343.9,242.5 181.1,148.4"/>
							 	</g>
							 </svg>
							}	
						<RichText
							tagName="span"
							onChange={ onChangeContent }
							value={ content }
						/>
						</a>
					</div>
					</>
				)}
			</div>
		</>
	);
}
