/**
 * External dependencies
 */
import { has } from 'lodash';
import { decodeEntities } from '@wordpress/html-entities';

/**
 * WordPress dependencies
 */
import { __, sprintf } from '@wordpress/i18n';
import { Fragment } from '@wordpress/element';

/**
 * Internal dependencies
 */
import WrappedSection from './wrapped-section';

function MalwareDetails( { results } ) {
	if ( ! has( results, [ 'MALWARE', 'WARN' ] ) ) {
		return <WrappedSection type="malware" status="clean" description={ __( 'Malware', 'better-wp-security' ) } />;
	}

	return (
		<WrappedSection type="malware" status="warn" description={ __( 'Malware', 'better-wp-security' ) }>
			<ul>
				{ results.MALWARE.WARN.map( ( entry, i ) => {
					let [ message, url ] = entry[ 0 ].split( ':', 2 );
					message = message.trim();
					url = url.trim();

					switch ( message.toLowerCase() ) {
						case 'security warning in the url':
							message = __( 'Security warning in the URL', 'better-wp-security' );
							break;
						case 'malware found on url':
							message = __( 'Malware found on URL', 'better-wp-security' );
							break;
					}

					let payload;

					if ( url.substring( 0, 5 ) === '&amp;' ) {
						payload = decodeEntities( url );
						url = results.itsec_site ? results.itsec_site.url : '/';
					}

					let details;
					const parts = entry[ 1 ].split( '\n', 2 );

					if ( parts[ 1 ] ) {
						const detailsMatch = parts[ 0 ].match( /(.+)\. Details: (.+)/ );

						if ( detailsMatch ) {
							let type = detailsMatch[ 1 ];
							const docsUrl = detailsMatch[ 2 ];

							if ( '*Known Spam detected' === type ) {
								type = __( '*Known Spam detected', 'better-wp-security' );
							}

							details = (
								<Fragment>
									<br />
									{ sprintf( __( 'Type: %s', 'better-wp-security' ), type ) }
									<br />
									{ __( 'Documentation:', 'better-wp-security' ) }
									<a href={ docsUrl } target="_blank" rel="noopener noreferrer">{ docsUrl }</a>
								</Fragment>
							);
						}

						const payloadMatch = decodeEntities( parts[ 1 ].trim() ).match( /<div id='HiddenDiv'>(.+)<\/div>/ );

						if ( payloadMatch ) {
							payload = payloadMatch[ 1 ];
						}
					}

					return (
						<li className="itsec-malware-scan-warn" key={ i }>
							<span>
								{ message }
								<br />
								{ __( 'Infected URL:', 'better-wp-security' ) }
								<a href={ url } target="_blank" rel="noopener noreferrer">{ url }</a>
								{ details }
								{ payload && (
									<Fragment>
										<br />
										{ __( 'Payload:', 'better-wp-security' ) }
										<pre>{ payload }</pre>
									</Fragment>
								) }
							</span>
						</li>
					);
				} ) }
			</ul>
		</WrappedSection>
	);
}

export default MalwareDetails;
