import Board from "../../comment/board";
import React from 'react'
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import allowedBlocks from './../component/compatibility/allowedBlocks';
import classnames from 'classnames';

import assign from "lodash.assign";
const { __ } = wp.i18n;                                                   // eslint-disable-line
const { isKeyboardEvent, displayShortcut } = wp.keycodes;
const { Fragment, useState } = wp.element;       					      // eslint-disable-line
const { BlockControls } = wp.blockEditor;                                 // eslint-disable-line
const { ToolbarGroup, ToolbarButton } = wp.components;                   // eslint-disable-line
const { addFilter } = wp.hooks;                                         // eslint-disable-line
const { createHigherOrderComponent, compose } = wp.compose;             // eslint-disable-line
const { getBlockType } = wp.data.select('core/blocks'); 			    // eslint-disable-line
const $ = jQuery;                                                       // eslint-disable-line
let isRichClassExist = document.activeElement.classList.contains('rich-text');     // eslint-disable-line                                              

const addNewAttribute = createHigherOrderComponent((BlockListBlock) => {
	return  (props) => {

		
		const { attributes, className } = props;
		let wrapperAttributes = {};
		let newDatatext = (attributes.datatext != undefined || attributes.datatext != '') ? attributes.datatext : '';
		let suggestion_id = (attributes.suggestion_id != undefined || attributes.suggestion_id != '') ? attributes.suggestion_id : '';
		let align_sg_id = (attributes.align_sg_id != undefined || attributes.align_sg_id != '') ? attributes.align_sg_id : '';
		let textAlign_sg_id = (attributes.textAlign_sg_id != undefined || attributes.textAlign_sg_id != '') ? attributes.textAlign_sg_id : '';
		let lock_sg_id = (attributes.lock_sg_id != undefined || attributes.lock_sg_id != '') ? attributes.lock_sg_id : '';
		let width_sg_id = (attributes.width_sg_id != undefined || attributes.width_sg_id != '') ? attributes.width_sg_id : '';
		let url_sg_id = (attributes.url_sg_id != undefined || attributes.url_sg_id != '') ? attributes.url_sg_id : '';
		let tracks_sg_id = (attributes.tracks_sg_id != undefined || attributes.tracks_sg_id != '') ? attributes.tracks_sg_id : '';
		let contentPosition_sg_id = (attributes.contentPosition_sg_id != undefined || attributes.contentPosition_sg_id != '') ? attributes.contentPosition_sg_id : '';
		let style_sg_id = (attributes.style_sg_id != undefined || attributes.style_sg_id != '') ? attributes.style_sg_id : '';
		let minHeight_sg_id = (attributes.minHeight_sg_id != undefined || attributes.minHeight_sg_id != '') ? attributes.minHeight_sg_id : '';
		let block_align = (attributes.align != undefined || attributes.align != '') ? attributes.align : '';
		let link_sg_id = (attributes.link_sg_id != undefined || attributes.link_sg_id != '') ? attributes.link_sg_id : '';
		let table_style_sg_id = (attributes.table_style_sg_id != undefined || attributes.table_style_sg_id != '') ? attributes.table_style_sg_id : '';

		if (suggestion_id) {
			wrapperAttributes.suggestion_id = suggestion_id;
		}
		if (align_sg_id) {
			wrapperAttributes.align_sg_id = align_sg_id;
		}
		if (textAlign_sg_id) {
			wrapperAttributes.textAlign_sg_id = textAlign_sg_id;
		}
		if (lock_sg_id) {
			wrapperAttributes.lock_sg_id = lock_sg_id;
		}
		if (width_sg_id) {
			wrapperAttributes.width_sg_id = width_sg_id;
		}
		if (url_sg_id) {
			wrapperAttributes.url_sg_id = url_sg_id;
		}
		if (tracks_sg_id) {
			wrapperAttributes.tracks_sg_id = tracks_sg_id;
		}
		if (contentPosition_sg_id) {
			wrapperAttributes.contentPosition_sg_id = contentPosition_sg_id;
		}
		if (style_sg_id) {
			wrapperAttributes.style_sg_id = style_sg_id;
		}
		if (minHeight_sg_id) {
			wrapperAttributes.minHeight_sg_id = minHeight_sg_id;
		}
		if (block_align) {
			wrapperAttributes.block_align = "align"+block_align;
		}
		if (link_sg_id) {
			wrapperAttributes.link_sg_id = link_sg_id;
		}
		if (table_style_sg_id) {
			wrapperAttributes.table_style_sg_id = table_style_sg_id;
		}
		
		//User can comment on whole block/@author Pooja Bhimani/@since 2.0.4.6
		if ((allowedBlocks.text).includes(props.name) ) {
			if(attributes.datatext && attributes?.suggestion_id ){
				return (
					<BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes, 'datatext': newDatatext, 'data-rich-text-format-boundary': true, 'suggestion_id': suggestion_id}} className={classnames(className, 'cf-onwhole-block__comment')}/>

				);
			} else if (attributes.datatext){
				return (
					<BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes, 'datatext': newDatatext, 'data-rich-text-format-boundary': true}} className={classnames(className, 'cf-onwhole-block__comment')}/>

				);
			} else if(attributes.suggestion_id ){
			
				return (
					<BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes, 'suggestion_id': suggestion_id }} />
				  
				);
		  	} else{
				return (<BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes}} />);
			}
			
		} else if(attributes.datatext && attributes?.suggestion_id){
			return (
				<BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes, 'datatext': newDatatext, 'data-rich-text-format-boundary': true, 'suggestion_id': suggestion_id}} className={classnames(className, 'cf-onwhole-block__comment')}/>

			);
		}
		
		if(attributes.datatext && attributes?.suggestion_id ){ // For block level suggestion functionality @author / Mayank Jain - @since 3.4 
			return <BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes, 'datatext': newDatatext, 'data-rich-text-format-boundary': true, 'suggestion_id': suggestion_id }} className={classnames(className, 'commentIcon')} />;
		
		} else if (attributes.datatext) {	
			return <BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes, 'datatext': newDatatext, 'data-rich-text-format-boundary': true }} className={classnames(className, 'commentIcon')} />;
		
		} else if( attributes?.suggestion_id ) {  // For block level suggestion functionality @author / Mayank Jain - @since 3.4
			return <BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes, 'suggestion_id': suggestion_id }} />;
	    
		} 
		else if( block_align && attributes?.name?.startsWith('acf/')) {  // For ACF Blocks Width functionality @author / Pitam Dey - @since 4.3
			return <BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes}} className={classnames(className, 'align'+block_align)} />;
	    
		} 
		else {
			return <BlockListBlock {...props} wrapperProps={{ ...wrapperAttributes}} />;
		}
	};
}, 'addNewAttribute');

wp.hooks.addFilter(
    'editor.BlockListBlock',
    'mdComment/add-new-attribute',
    addNewAttribute,
);

addFilter(
    'editor.BlockListBlock',
    'multicollab/block-suggestion/mc-whole-block-comment',
    ( OriginalComponent ) => ( props ) => {

      const component = <OriginalComponent { ...props } />;
	  let suggestionClass = '', suggestionID = '', blockclientId='';
		if (props.attributes?.className && props.attributes.className.includes('blockAdded')) {
			suggestionClass = 'cf-icon__addBlocks';
		} else if (props.attributes?.className && props.attributes.className.includes('blockremove')) {
			suggestionClass = 'cf-icon__removeBlocks';
		} else {
			suggestionClass = '';
		}
		if ('' !== suggestionClass) {
			suggestionID = props.attributes?.suggestion_id || '';
			blockclientId = props.block?.clientId || '';
		}
      if (props.attributes?.datatext && (allowedBlocks.text).includes(props.name) && '' === suggestionClass) {
		return (
			<div className='cf-wrapperblock__suggestion'>  
			  { component }
			  <span className={'cf-icon-wholeblock__comment'} datatext = {props.attributes.datatext} ></span>
			</div>
		  );
      } else if (props.attributes?.datatext && '' !== suggestionClass){
		if( '1' !== multicollabRolePermissions.hide_comment ) {
			return (
				<div className='cf-wrapperblock__suggestion'>  
				  { component }
				  <span className={'cf-icon-wholeblock__comment'} data-blockclient_id={blockclientId} data-suggestion_id={suggestionID} datatext = {props.attributes.datatext}></span>
				</div>
			  );
		} else {
			return (
				<div className='cf-wrapperblock__suggestion'>  
				  { component }
				  <span className={suggestionClass} data-blockclient_id={blockclientId} data-suggestion_id={suggestionID} datatext = {props.attributes.datatext}></span>
				</div>
			  );
		}
		
	  }else if ('' !== suggestionClass){
		return (
			        <div className='cf-wrapperblock__suggestion'>  
			          { component }
			          <span className={suggestionClass} data-blockclient_id={blockclientId} data-suggestion_id={suggestionID}></span>
			        </div>
			      );
	  }else {
        return component;
      }	


    }
);

addFilter(
	'blocks.registerBlockType',
	'mdComment/nontextBlock-extension',
	 (settings, name) => {
		const attributes = {
			...settings.attributes,
			datatext: {
				type: 'string',
			},
			suggestion_id: {    // For block level suggestion functionality @author / Mayank Jain - @since 3.4 
				type: 'string',
			},
			align_sg_id: {    // For align feature suggestion functionality @author - Mayank Jain - @since 3.6
				type: 'string',
			},
			textAlign_sg_id: {    // For block level suggestion functionality @author - Mayank Jain - @since 3.6
				type: 'string',
			},
			lock_sg_id: {    // For block level suggestion functionality @author - Mayank Jain - @since 3.6
				type: 'string',
			},
			width_sg_id: {
				type: 'string',
			},
			url_sg_id: {
				type: 'string'
			},
			tracks_sg_id: {
				type: 'string'
			},
			contentPosition_sg_id: {
				type: 'string'
			},
			style_sg_id: {
				type: 'string'
			},
			minHeight_sg_id: {
				type: 'string'
			},
			link_sg_id: {
				type: 'string'
			},
			table_style_sg_id: {
				type: 'string'
			}
		};
		return { ...settings, attributes };
	}
);

function enableClassNameAttribute(settings, name) {

	// Addeed memberpress condition for Github issue: 1631
    if ( ['core/block', 'core/freeform', 'core/more', 'core/nextpage', 'core/html', 'core/shortcode'].indexOf(name) !== -1 || name?.startsWith('memberpress/') ){
        settings.supports = {
            ...settings.supports,
            className: true,
        };
		settings.attributes = {
            ...settings.attributes,
            className: {
				type: 'string',
			},
        };
    }
    if ( name?.startsWith('learndash/') ){
				settings.supports = {
		            ...settings.supports,
		            className: true,
					customClassName: true,
		        };
				settings.attributes = {
		            ...settings.attributes,
		            className: {
						type: 'string',
					},
		        };
			}
    return settings;
}
wp.hooks.addFilter('blocks.registerBlockType', 'mdComment/enable-classname', enableClassNameAttribute);

wp.hooks.addFilter(
  "blocks.registerBlockType",
  "mdComment/table-block-custom-attr",
  (settings) => {
    // If the block isn't a `core/table` block, we return the same settings
    if (settings.name != "core/table") return settings;

    // Else, we extend the attributes
    settings.attributes = {
      ...settings.attributes,
      newBody: {
        type: "array",
        default: [],
      },
      customBody: {
        type: "array",
        default: [],
      },
    };

    return settings;
  }
);



addFilter('blocks.getSaveContent.extraProps', 'mdComment/saveDatatext', function (extraProps, blockType, attributes) {
	var postMetas = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'meta' );
	if(attributes && attributes.suggestion_id && postMetas?._sb_is_suggestion_mode){ // For block level suggestion functionality @author / Mayank Jain - @since 3.4 ========== 
		Object.assign(extraProps, {
			suggestion_id: '',
		});
	}
	if(attributes && attributes.align_sg_id && postMetas?._sb_is_suggestion_mode){ // For align feature suggestion @author - Mayank / since @3.6
		Object.assign(extraProps, {
			align_sg_id: '',
		});
	}
	if(attributes && attributes.textAlign_sg_id && postMetas?._sb_is_suggestion_mode){ // For text align feature suggestion @author - Mayank / since @3.6
		Object.assign(extraProps, {
			textAlign_sg_id: '',
		});
	}
	if(attributes && attributes.lock_sg_id && postMetas?._sb_is_suggestion_mode){ // For lock feature suggestion @author - Mayank / since @3.6
		Object.assign(extraProps, {
			lock_sg_id: '',
		});
	}
	if(attributes && attributes.width_sg_id && postMetas?._sb_is_suggestion_mode){ // For block width suggestion feature
		Object.assign(extraProps, {
			width_sg_id: '',
		});
	}
	if(attributes && attributes.url_sg_id && postMetas?._sb_is_suggestion_mode){ // For block url suggestion feature
		Object.assign(extraProps, {
			url_sg_id: '',
		});
	}
	if(attributes && attributes.tracks_sg_id && postMetas?._sb_is_suggestion_mode){ // For block tracks suggestion feature
		Object.assign(extraProps, {
			tracks_sg_id: '',
		});
	}
	if(attributes && attributes.contentPosition_sg_id && postMetas?._sb_is_suggestion_mode){ // For block content position suggestion feature
		Object.assign(extraProps, {
			contentPosition_sg_id: '',
		});
	}
	if(attributes && attributes.table_style_sg_id && postMetas?._sb_is_suggestion_mode){ // For block content position suggestion feature
		Object.assign(extraProps, {
			table_style_sg_id: '',
		});
	}
	if(attributes && attributes.style_sg_id && postMetas?._sb_is_suggestion_mode){ // For block tracks suggestion feature
		Object.assign(extraProps, {
			style_sg_id: '',
		});
	}
	if(attributes && attributes.minHeight_sg_id && postMetas?._sb_is_suggestion_mode){ // For block tracks suggestion feature
		Object.assign(extraProps, {
			minHeight_sg_id: '',
		});
	}
	if(attributes && attributes.link_sg_id && postMetas?._sb_is_suggestion_mode){ // For block media link suggestion feature
		Object.assign(extraProps, {
			link_sg_id: '',
		});
	}

	if ((allowedBlocks.text).includes(blockType.name)  || isRichClassExist) {
		// return extraProps;
	} else {
		if ('undefined' !== attributes.datatext || null !== attributes.datatext) {
			
			Object.assign(extraProps, {
				datatext: attributes.datatext,
			});
			
			// return extraProps;
		}
	}
	return extraProps;
});
const customAttributes = createHigherOrderComponent(BlockEdit => {
	return (props) => {
		<BlockEdit {...props} />
	}

},customAttributes);


export default compose()(customAttributes);
