/*!
 * VisualEditor DebugBar class.
 *
 * @copyright See AUTHORS.txt
 */

/**
 * Debug bar
 *
 * @class
 * @extends OO.ui.Element
 *
 * @constructor
 * @param {ve.ui.Surface} surface Surface to debug
 * @param {Object} [config] Configuration options
 */
ve.ui.DebugBar = function VeUiDebugBar( surface, config = {} ) {
	// Parent constructor
	ve.ui.DebugBar.super.call( this, config );

	this.surface = surface;

	this.$commands = $( '<div>' ).addClass( 've-ui-debugBar-commands' );
	this.$linmodData = $( '<td>' ).addClass( 've-ui-debugBar-dump-linmod-data' );
	this.$viewTree = $( '<td>' ).addClass( 've-ui-debugBar-view-tree' );
	this.$modelTree = $( '<td>' ).addClass( 've-ui-debugBar-model-tree' );

	const closeButton = new OO.ui.ButtonWidget( {
		icon: 'close',
		label: ve.msg( 'visualeditor-debugbar-close' )
	} );

	// Widgets
	this.selectionLabel = new OO.ui.LabelWidget( { classes: [ 've-ui-debugBar-selectionLabel' ] } );

	this.logRangeButton = new OO.ui.ButtonWidget( { label: ve.msg( 'visualeditor-debugbar-logrange' ), disabled: true } );
	this.showModelToggle = new OO.ui.ToggleButtonWidget( { label: ve.msg( 'visualeditor-debugbar-showmodel' ) } );
	this.updateModelToggle = new OO.ui.ToggleButtonWidget( { label: ve.msg( 'visualeditor-debugbar-updatemodel' ) } );
	this.transactionsToggle = new OO.ui.ToggleButtonWidget( { label: ve.msg( 'visualeditor-debugbar-showtransactions' ) } );
	this.testSquasherToggle = new OO.ui.ToggleButtonWidget( { label: ve.msg( 'visualeditor-debugbar-testsquasher' ) } );
	this.inputDebuggingToggle = new OO.ui.ToggleButtonWidget( { label: ve.msg( 'visualeditor-debugbar-inputdebug' ) } ).setValue( ve.inputDebug );
	this.filibusterToggle = new OO.ui.ToggleButtonWidget( { label: ve.msg( 'visualeditor-debugbar-startfilibuster' ) } );
	this.buildTestButton = new OO.ui.ButtonWidget( { label: ve.msg( 'visualeditor-debugbar-buildtest' ) } );

	this.$dump =
		$( '<div>' ).addClass( 've-ui-debugBar-dump' ).append(
			this.updateModelToggle.$element,
			$( '<table>' ).append(
				$( '<thead>' ).append(
					$( '<th>' ).text( 'Linear model data' ),
					$( '<th>' ).text( 'View tree' ),
					$( '<th>' ).text( 'Model tree' )
				),
				$( '<tbody>' ).append(
					$( '<tr>' ).append(
						this.$linmodData, this.$viewTree, this.$modelTree
					)
				)
			)
		).addClass( 'oo-ui-element-hidden' );

	this.$testCase = $( '<div>' ).addClass( 've-ui-debugBar-testCase oo-ui-element-hidden' );

	this.$transactions = $( '<div>' ).addClass( 've-ui-debugBar-transactions' );

	this.$filibuster = $( '<div>' ).addClass( [ 've-ui-debugBar-filibuster', 'oo-ui-element-hidden' ] );

	// Events
	this.logRangeButton.on( 'click', this.onLogRangeButtonClick.bind( this ) );
	this.showModelToggle.on( 'change', this.onShowModelToggleChange.bind( this ) );
	this.updateModelToggle.on( 'change', this.onUpdateModelToggleChange.bind( this ) );
	this.inputDebuggingToggle.on( 'change', this.onInputDebuggingToggleChange.bind( this ) );
	this.filibusterToggle.on( 'click', this.onFilibusterToggleClick.bind( this ) );
	this.transactionsToggle.on( 'change', this.onTransactionsToggleChange.bind( this ) );
	this.testSquasherToggle.on( 'change', this.onTestSquasherToggleChange.bind( this ) );
	this.buildTestButton.on( 'click', this.onBuildTestButtonClick.bind( this ) );
	closeButton.on( 'click', this.$element.remove.bind( this.$element ) );

	this.onHistoryDebounced = ve.debounce( this.onHistory.bind( this ) );

	this.getSurface().getModel().connect( this, {
		select: 'onSurfaceSelect',
		history: 'onHistoryDebounced'
	} );
	this.onSurfaceSelect( this.getSurface().getModel().getSelection() );

	this.$element.addClass( 've-ui-debugBar' );
	this.$element.append(
		this.$commands.append(
			this.selectionLabel.$element,
			this.logRangeButton.$element,
			$( this.constructor.static.dividerTemplate ),
			this.showModelToggle.$element,
			this.inputDebuggingToggle.$element,
			this.filibusterToggle.$element,
			this.transactionsToggle.$element,
			this.testSquasherToggle.$element,
			this.buildTestButton.$element,
			$( this.constructor.static.dividerTemplate ),
			closeButton.$element
		),
		this.$dump,
		this.$testCase,
		this.$transactions,
		this.$filibuster
	);

	this.target = null;
};

/* Inheritance */

OO.inheritClass( ve.ui.DebugBar, OO.ui.Element );

/**
 * Divider HTML template
 *
 * @property {string}
 */
ve.ui.DebugBar.static.dividerTemplate = '<span class="ve-ui-debugBar-commands-divider">&nbsp;</span>';

/**
 * Get surface the debug bar is attached to
 *
 * @return {ve.ui.Surface|null}
 */
ve.ui.DebugBar.prototype.getSurface = function () {
	return this.surface;
};

/**
 * Handle select events on the attached surface
 *
 * @param {ve.dm.Selection} selection
 */
ve.ui.DebugBar.prototype.onSurfaceSelect = function () {
	// Do not trust the emitted selection: nested emits can invalidate it. See T145938.
	const selection = this.surface.model.getSelection();
	this.selectionLabel.setLabel( selection.getDescription() );
	this.logRangeButton.setDisabled( !(
		( selection instanceof ve.dm.LinearSelection && !selection.isCollapsed() ) ||
		selection instanceof ve.dm.TableSelection
	) );
};

/**
 * Handle history events on the attached surface
 */
ve.ui.DebugBar.prototype.onHistory = function () {
	if ( this.transactionsToggle.getValue() ) {
		this.updateTransactions();
	}
};

/**
 * Handle click events on the log range button
 *
 * @param {jQuery.Event} e
 */
ve.ui.DebugBar.prototype.onLogRangeButtonClick = function () {
	const selection = this.getSurface().getModel().getSelection(),
		documentModel = this.getSurface().getModel().getDocument();
	if ( selection instanceof ve.dm.LinearSelection || selection instanceof ve.dm.TableSelection ) {
		selection.getRanges( documentModel ).forEach( ( range ) => {
			ve.dir( this.getSurface().view.documentView.model.data.slice( range.start, range.end ) );
		} );
	}
};

/**
 * Handle change events on the show model toggle
 *
 * @param {boolean} value
 */
ve.ui.DebugBar.prototype.onShowModelToggleChange = function ( value ) {
	if ( value ) {
		this.updateDump();
	} else {
		this.updateModelToggle.setValue( false );
	}
	this.$dump.toggleClass( 'oo-ui-element-hidden', !value );
};

/**
 * Update the model dump
 */
ve.ui.DebugBar.prototype.updateDump = function () {
	const surface = this.getSurface(),
		documentModel = surface.getModel().getDocument(),
		documentView = surface.getView().getDocument();

	// Linear model dump
	const $linmodData = this.generateListFromLinearData( documentModel.data );
	this.$linmodData.empty().append( $linmodData );
	const $modelTree = this.generateListFromNode( documentModel.getDocumentNode() );
	this.$modelTree.empty().append( $modelTree );
	const $viewTree = this.generateListFromNode( documentView.getDocumentNode() );
	this.$viewTree.empty().append( $viewTree );
};

/**
 * Get an ordered list representation of some linear data
 *
 * @param {ve.dm.LinearData} linearData Linear data
 * @return {jQuery} Ordered list
 */
ve.ui.DebugBar.prototype.generateListFromLinearData = function ( linearData ) {
	const $ol = $( '<ol>' ).attr( 'start', '0' ),
		data = linearData.data;

	let $chunk, prevType, prevAnnotations, $annotations;
	data.forEach( ( element, i ) => {
		const $label = $( '<span>' );
		let annotations = null, attributes = null;
		let text;
		if ( element.type ) {
			$label.addClass( 've-ui-debugBar-dump-element' );
			text = element.type;
			annotations = element.annotations;
			attributes = element.attributes || null;
		} else if ( Array.isArray( element ) ) {
			$label.addClass( 've-ui-debugBar-dump-achar' );
			[ text, annotations ] = element;
		} else {
			$label.addClass( 've-ui-debugBar-dump-char' );
			text = element;
		}

		$label.text( /\S/.test( text ) ? text : '\u00a0' );

		if ( $chunk && !prevType && !element.type && OO.compare( prevAnnotations, annotations ) ) {
			// This is a run of text with identical annotations. Continue current chunk.
			$chunk.append( $label );
		} else {
			// End current chunk, if any.
			if ( $chunk ) {
				$ol.append( $chunk.append( $annotations ) );
				$annotations = null;
			}

			// Begin a new chunk
			$chunk = $( '<li>' ).attr( 'value', i ).append( $label );
			if ( annotations || attributes ) {
				$annotations = $( '<span>' ).addClass( 've-ui-debugBar-dump-note' ).text(
					( annotations ?
						JSON.stringify(
							this.getSurface().getModel().getDocument().getStore().values( annotations )
								.map( ( ann ) => ann.getComparableObject() )
						) : '' ) +
					( attributes ? JSON.stringify( attributes ) : '' )
				);
			}

			if ( element.type === 'internalList' ) {
				const internalList = this.getSurface().getModel().getDocument().internalList;

				$chunk.append(
					$( '<span>' ).addClass( 've-ui-debugBar-dump-note' ).text(
						' keyIndexes: ' + JSON.stringify( internalList.keyIndexes )
					)
				);
			}

			if ( element.type === 'internalItem' ) {
				const index = this.getSurface()
					.getModel()
					.getDocument()
					.internalList
					.listNode
					.children
					.findIndex( ( node ) => node.element === element );

				$chunk.append(
					$( '<span>' ).addClass( 've-ui-debugBar-dump-note' ).text( ' index: ' + index + ' ' )
				);
			}
		}

		prevType = element.type;
		prevAnnotations = annotations;
	} );

	// End current chunk, if any.
	if ( $chunk ) {
		$ol.append( $chunk.append( $annotations ) );
	}

	return $ol;
};

/**
 * Generate an ordered list describing a node
 *
 * @param {ve.Node} node
 * @return {jQuery} Ordered list
 */
ve.ui.DebugBar.prototype.generateListFromNode = function ( node ) {
	const $ol = $( '<ol>' ).attr( 'start', '0' );

	node.children.forEach( ( child ) => {
		const $li = $( '<li>' ).append( $( '<span>' ).addClass( 've-ui-debugBar-dump-element' )
			.text( child.type ) );

		if ( child.length !== undefined ) {
			$li.append( $( '<span>' ).addClass( 've-ui-debugBar-dump-note' )
				.text( '(' + child.length + ')' ) );
		}

		if ( child.children ) {
			// eslint-disable-next-line no-jquery/no-append-html
			$li.append( this.generateListFromNode( child ) );
		}

		$ol.append( $li );
	} );
	return $ol;
};

/**
 * Handle change events on the update model toggle button
 *
 * @param {boolean} value
 */
ve.ui.DebugBar.prototype.onUpdateModelToggleChange = function ( value ) {
	if ( value ) {
		this.updateDump();
		this.getSurface().model.connect( this, { documentUpdate: 'updateDump' } );
	} else {
		this.getSurface().model.disconnect( this, { documentUpdate: 'updateDump' } );
	}
};

/**
 * Handle click events on the input debugging toggle button
 *
 * @param {boolean} value
 */
ve.ui.DebugBar.prototype.onInputDebuggingToggleChange = function ( value ) {
	const surfaceModel = this.getSurface().getModel(),
		selection = surfaceModel.getSelection();

	ve.inputDebug = value;

	// Clear the cursor before rebuilding, it will be restored later
	surfaceModel.setNullSelection();
	setTimeout( () => {
		surfaceModel.getDocument().rebuildTree();
		surfaceModel.setSelection( selection );
	} );
};

/**
 * Handle click events on the filibuster toggle button
 *
 * @param {jQuery.Event} e
 */
ve.ui.DebugBar.prototype.onFilibusterToggleClick = function () {
	const value = this.filibusterToggle.getValue();
	if ( value ) {
		this.filibusterToggle.setLabel( ve.msg( 'visualeditor-debugbar-stopfilibuster' ) );
		this.$filibuster.off( 'click' );
		this.$filibuster.empty();
		ve.initFilibuster();
		ve.filibuster.start();
	} else {
		ve.filibuster.stop();
		// eslint-disable-next-line no-jquery/no-html
		this.$filibuster.html( ve.filibuster.getObservationsHtml() );
		this.$filibuster.on( 'click', ( e ) => {
			const $li = $( e.target ).closest( '.ve-filibuster-frame' );

			// eslint-disable-next-line no-jquery/no-class-state
			if ( $li.hasClass( 've-filibuster-frame-expandable' ) ) {
				$li.removeClass( 've-filibuster-frame-expandable' );
				const path = $li.data( 've-filibuster-frame' );
				if ( !path ) {
					return;
				}
				$li.children( 'span' ).replaceWith(
					$( ve.filibuster.getObservationsHtml( path ) )
				);
				// eslint-disable-next-line no-jquery/no-class-state
				$li.toggleClass( 've-filibuster-frame-expanded' );
			} else if ( $li.children( 'ul' ).length ) {
				// eslint-disable-next-line no-jquery/no-class-state
				$li.toggleClass( 've-filibuster-frame-collapsed ve-filibuster-frame-expanded' );
			}
		} );
		this.filibusterToggle.setLabel( ve.msg( 'visualeditor-debugbar-startfilibuster' ) );
	}
	this.$filibuster.toggleClass( 'oo-ui-element-hidden', !!value );
};

/**
 * Handle click events on the filibuster toggle button
 *
 * @param {boolean} value
 */
ve.ui.DebugBar.prototype.onTransactionsToggleChange = function ( value ) {
	if ( value ) {
		this.updateTransactions();
	}
	this.$transactions.toggleClass( 'oo-ui-element-hidden', !value );
};

/**
 * Handle click events on the test squasher toggle button
 *
 * @param {boolean} value
 */
ve.ui.DebugBar.prototype.onTestSquasherToggleChange = function ( value ) {
	const doc = this.getSurface().getModel().getDocument();
	if ( value ) {
		doc.connect( this, { transact: 'testSquasher' } );
		this.testSquasher();
	} else {
		doc.disconnect( this, { transact: 'testSquasher' } );
	}
};

/**
 * Handle click events on the build test button
 *
 * @param {jQuery.Event} e
 */
ve.ui.DebugBar.prototype.onBuildTestButtonClick = function () {
	this.$testCase
		.empty()
		.append( $( '<h2>' ).text( 'Test case' ) )
		.append( $( '<pre>' ).attr( 'contenteditable', 'true' ).text( this.generateTestCase() ) );
	this.$testCase.removeClass( 'oo-ui-element-hidden' );
};

ve.ui.DebugBar.prototype.generateTestCase = function () {
	const surfaceModel = this.getSurface().getModel();
	const currentDocument = surfaceModel.getDocument();

	const transactions = surfaceModel.getHistory()
		.map( ( item ) => item.transactions )
		.reduce( ( acc, txs ) => acc.concat( txs ), [] );

	const originalHtml = currentDocument.htmlDocument.body.innerHTML;
	// FIXME: This all results in slightly different data than after the
	// original MW Target load, which may cause transactions to line up
	// incorrectly.
	const originalDocument = ve.createDocumentFromHtml( originalHtml );
	// Adapted from mw.libs.ve.unwrapParsoidSections
	const unwrapSections = ( doc ) => {
		Array.prototype.forEach.call( doc.querySelectorAll( 'section' ), ( section ) => {
			const parent = section.parentNode;
			while ( section.firstChild ) {
				parent.insertBefore( section.firstChild, section );
			}
			parent.removeChild( section );
		} );
	};
	unwrapSections( originalDocument );

	const removeHashes = ( item ) => ve.deleteProp( item, 'originalDomElementsHash' );
	const serializeToJson = ( data ) => JSON.stringify( data, null, '\t' );
	const getBodyContent = ( htmlDocument ) => htmlDocument.body.innerHTML;
	const wrapHtmlLiteral = ( htmlString ) => JSON.stringify( htmlString );
	const indentLines = ( indentation, text ) => text.replace( /^.*$/gm, indentation + '$&' );
	const repairAllUndefined = ( sub ) => sub.replace( /\bnull\b/g, 'undefined' );
	const repairWhitespaceUndefined =
		( text ) => text.replace( /whitespace([[:"{,\s]|\\.|null)+/gi, repairAllUndefined );

	const serializeTransactionBuilder = ( txs ) => {
		if ( txs.length === 0 ) {
			return undefined;
		}
		const serializeTransaction = ( tx ) => 'model.commit( ve.dm.Transaction.static.deserialize( ' +
				JSON.stringify( tx ) +
			' ) );';
		const txStatements = txs.map( serializeTransaction );
		return '( model ) => {\n' +
			indentLines( '\t', txStatements.join( '\n' ) ) +
			'\n\t}';
	};

	// Adapted from ve.test.utils: we want to run methods such as i18n message
	// translation in the dummy context to match the way the test will eventually
	// be run.
	const swapDummyPlatform = ( next ) => {
		const DummyPlatform = function DummyPlatform() {
			DummyPlatform.super.apply( this, arguments );
		};
		OO.inheritClass( DummyPlatform, ve.init.platform.constructor );
		DummyPlatform.prototype.getMessage = ( ...args ) => args.join( ',' );

		const activePlatform = ve.init.platform;
		ve.init.platform = new DummyPlatform();
		try {
			return next();
		} finally {
			ve.init.platform = activePlatform;
			OO.ui.msg = ve.init.platform.getMessage.bind( ve.init.platform );
		}
	};

	let originalData = ve.dm.converter.getModelFromDom( originalDocument )
		.getFullData( undefined, 'roundTrip' );
	originalData = ve.copy( originalData );
	originalData = ve.copy( originalData, null, removeHashes );

	const strippedData = ve.copy( ve.copy( currentDocument.getData() ), null, removeHashes );
	const strippedCurrentDocument = new ve.dm.Document( strippedData );

	const testCaseData = {
		data: repairWhitespaceUndefined( serializeToJson( originalData ) ),
		modify: serializeTransactionBuilder( transactions ),
		// Original document as DOM from Parsoid.
		body: wrapHtmlLiteral( getBodyContent( originalDocument ) ),
		// Current document rendered to DOM in parser mode.
		fromDataBody: wrapHtmlLiteral( getBodyContent(
			ve.dm.converter.getDomFromModel( strippedCurrentDocument ) ) ),
		// Current document rendered including stored incoming HTML.
		normalizedBody: wrapHtmlLiteral( getBodyContent(
			ve.dm.converter.getDomFromModel( surfaceModel.getDocument() ) ) ),
		// Current document rendered to DOM in clipboard mode.
		clipboardBody: wrapHtmlLiteral( getBodyContent(
			swapDummyPlatform(
				() => ve.dm.converter.getDomFromModel( strippedCurrentDocument, ve.dm.Converter.static.CLIPBOARD_MODE )
			) ) ),
		// Current document rendered to DOM in preview mode.
		previewBody: wrapHtmlLiteral( getBodyContent(
			swapDummyPlatform(
				() => ve.dm.converter.getDomFromModel( strippedCurrentDocument, ve.dm.Converter.static.PREVIEW_MODE )
			) ) ),
		innerWhitespace: repairAllUndefined( serializeToJson(
			currentDocument.getInnerWhitespace() ) ),
		preserveAnnotationDomElements: 'true'
	};
	return '{\n' +
		indentLines( '\t',
			Object.entries( testCaseData )
				.filter( ( [ , value ] ) => value )
				.map( ( [ key, value ] ) => key + ':\n' + indentLines( '\t', value ) )
				.join( ',\n' )
		) + '\n}';
};

/**
 * Update the transaction dump
 */
ve.ui.DebugBar.prototype.updateTransactions = function () {
	const surface = this.getSurface(),
		$transactionsList = $( '<ol>' );

	surface.getModel().getHistory().forEach( ( item ) => {
		const $state = $( '<ol>' ).appendTo( $( '<li>' ).appendTo( $transactionsList ) );
		item.transactions.forEach( ( tx ) => {
			$state.append( $( '<li>' ).text( ve.summarizeTransaction( tx ) ) );
		} );
	} );

	this.$transactions.empty().append( $transactionsList );
};

ve.ui.DebugBar.prototype.testSquasher = function () {
	function squashTransactions( txs ) {
		return new ve.dm.Change(
			0,
			txs.map( ( tx ) => tx.clone() ),
			txs.map( () => new ve.dm.HashValueStore() ),
			{}
		).squash().txs;
	}

	const transactions = this.getSurface().getModel().getDocument().completeHistory.transactions;
	if ( transactions.length < 3 ) {
		// Nothing interesting here
		return;
	}

	const squashed = squashTransactions( transactions );
	for ( let i = 1, iLen = transactions.length - 1; i < iLen; i++ ) {
		const squashedBefore = squashTransactions( transactions.slice( 0, i ) );
		const squashedAfter = squashTransactions( transactions.slice( i ) );
		const doubleSquashed = squashTransactions( [ ...squashedBefore, ...squashedAfter ] );
		const dump = JSON.stringify( squashed );
		const doubleDump = JSON.stringify( doubleSquashed );
		if ( dump !== doubleDump ) {
			throw new Error( 'Discrepancy splitting at i=' + i );
		}
	}
};

/**
 * Destroy the debug bar
 */
ve.ui.DebugBar.prototype.destroy = function () {
	this.getSurface().getModel().disconnect();
	this.$element.remove();
};