/* globals jQuery:true, ajaxurl:true, sn_block_ui:true, secninScheduledScanner:true */
/**
 * Security Ninja - Scheduled Scanner
 * (c) Web factory 2015
 * Updated 2020 - Larsik Corp
 */

var logsLoaded = false;

function fetchLogs() {
	var data = {
		action: 'sn_ss_get_logs',
		nonce: secninScheduledScanner.nonce
	};

	jQuery.post( ajaxurl, data, function( response ) {
		if ( response.success ) {
			logsLoaded = true;
			jQuery( '#wf-sn-ss-log tbody' ).html( response.data );
		} else {
			jQuery( '#wf-sn-ss-log tbody' ).html( '<tr><td colspan="5"><span class="no-logs">' + response.data + '</span></td></tr>' );
		}
	} );
}

function maybeLoadLogs() {
	if ( window.location.hash !== '#sn_schedule' ) {
		return;
	}
	if ( logsLoaded ) {
		return;
	}
	jQuery( '#wf-sn-ss-log tbody' ).html( '<tr><td colspan="5"><span class="spinner is-active"></span> ' + secninScheduledScanner.strings.loading + '</td></tr>' );
	fetchLogs();
}

function whenSchedulerTabFocused() {
	if ( window.location.hash !== '#sn_schedule' ) {
		return;
	}
	maybeLoadLogs();
}

jQuery( document ).ready( function( $ ) {

	jQuery( window ).on( 'hashchange', whenSchedulerTabFocused );
	jQuery( document ).on( 'click', '#wf-sn-tabs a[href="#sn_schedule"]', function() {
		whenSchedulerTabFocused();
	} );
	if ( window.location.hash === '#sn_schedule' ) {
		whenSchedulerTabFocused();
	}

	// Run scheduler test via AJAX.
	jQuery( '#sn-ss-test' ).on( 'click', function() {
		SnDialog.confirm({
			message: secninScheduledScanner.strings.confirm_save_before_test
		}).then(function( ok ) {
			if ( ! ok ) {
				return;
			}
		var $testBtn = jQuery( '#sn-ss-test' );
		$testBtn.prop( 'disabled', true );

		var $output = jQuery( '#wf-ss-output' );
		$output.find( '.sn-ss-test-placeholder' ).remove();
		$output.show().empty();
		$output.append( '<p class="sn-ss-test-status">' +
			'<span class="spinner is-active" style="float:none;margin:0 6px 0 0;display:inline-block;"></span> ' +
			secninScheduledScanner.strings.running_status + '</p>' );
		$output.append( '<p id="sn-ss-timer" class="sn-ss-timer" style="margin:4px 0 0 22px;font-size:13px;color:#646970;"></p>' );

		var data = {
			action: 'sn_ss_cs_test',
			nonce: secninScheduledScanner.nonce
		};

		var startTime = Date.now();
		var timer = setInterval( function() {
			var elapsedSeconds = Math.floor( ( Date.now() - startTime ) / 1000 );
			$( '#wf-ss-output #sn-ss-timer' ).text( secninScheduledScanner.strings.time_elapsed_format.replace( '%d', elapsedSeconds ) );
		}, 1000 );

		function reenableButton() {
			clearInterval( timer );
			$testBtn.prop( 'disabled', false );
		}

		jQuery.ajax( {
			url: ajaxurl,
			type: 'POST',
			data: data,
			timeout: 600000,
			success: function( response ) {
				clearInterval( timer );
				$output.find( '.sn-ss-test-status' ).remove();
				$output.find( '#sn-ss-timer' ).remove();
				// Keep button disabled so user sees that something happened.
				$testBtn.prop( 'disabled', true );
				var msg = ( response.data && response.data.message ) ? response.data.message : secninScheduledScanner.strings.tasks_completed_fallback;
				$output.append( '<p class="sn-ss-test-message" style="margin:0 0 6px 0;font-weight:500;">' + msg + '</p>' );
				if ( response.data && response.data.note ) {
				$output.append( '<p class="sn-ss-test-note" style="margin:0;font-size:12px;">' + response.data.note + '</p>' );
				}
			},
			error: function( jqXHR, textStatus, errorThrown ) {
				reenableButton();
				$output.find( '.sn-ss-test-status' ).remove();
				$output.find( '#sn-ss-timer' ).remove();
				$output.append( '<p class="sn-ss-test-error" style="margin:0;color:#b32d2e;">' + secninScheduledScanner.strings.request_failed + '</p>' );
			}
		} );
		});
	} );

	// Truncate log table.
	$( '#wf-sn-ss-truncate-log' ).on( 'click', function() {
		SnDialog.confirm({
			message: secninScheduledScanner.strings.confirm_delete_logs,
			danger: true
		}).then(function( ok ) {
			if ( ! ok ) {
				return;
			}
			var data = {
				action: 'sn_ss_truncate_log',
				nonce: secninScheduledScanner.nonce
			};
			$.post( ajaxurl, data, function( response ) {
				if ( ! response ) {
					SnDialog.alert({ message: secninScheduledScanner.strings.bad_ajax_response });
				} else {
					fetchLogs();
				}
			} );
		});
		return false;
	} );

	// Security Ninja results details.
	$( document ).on( 'click', '.ss-details-sn', function() {
		var $this = $( this );
		var data = {
			action: 'sn_ss_sn_details',
			nonce: secninScheduledScanner.nonce,
			row_id: $this.attr( 'data-row-id' )
		};
		var timestamp = $this.attr( 'data-timestamp' );

		$( '.ss-details-sn' ).prop( 'disabled', true );
		$this.append( '<span class="spinner is-active"></span>' );

		$.post( ajaxurl, data, function( response ) {
			$( '.spinner' ).remove();
			$( '.ss-details-sn' ).prop( 'disabled', false );
			if ( ! response ) {
				SnDialog.alert({ message: secninScheduledScanner.strings.bad_ajax_response });
			} else {
				SnDialog.open({
					title: secninScheduledScanner.strings.dialog_title_sn.replace( '%s', timestamp ),
					bodyHtml: response,
					size: 'large'
				});
			}
		} ).fail( function() {
			SnDialog.alert({ message: secninScheduledScanner.strings.error_try_again });
			$( '.spinner' ).remove();
			$( '.ss-details-sn' ).prop( 'disabled', false );
		} );
		return false;
	} );

	// Core Scanner results details.
	$( document ).on( 'click', '.ss-details-cs', function() {
		var $this = $( this );
		var data = {
			action: 'sn_ss_cs_details',
			row_id: $this.attr( 'data-row-id' ),
			nonce: secninScheduledScanner.nonce
		};
		var timestamp = $this.attr( 'data-timestamp' );

		$( '.ss-details-cs' ).prop( 'disabled', true );
		$this.append( '<span class="spinner is-active"></span>' );

		$.post( ajaxurl, data, function( response ) {
			$( '.spinner' ).remove();
			$( '.ss-details-cs' ).prop( 'disabled', false );
			if ( ! response ) {
				SnDialog.alert({ message: secninScheduledScanner.strings.bad_ajax_response });
			} else {
				SnDialog.open({
					title: secninScheduledScanner.strings.dialog_title_cs.replace( '%s', timestamp ),
					bodyHtml: response,
					size: 'large'
				});
			}
		} ).fail( function() {
			SnDialog.alert({ message: secninScheduledScanner.strings.error_try_again });
			$( '.spinner' ).remove();
			$( '.ss-details-cs' ).prop( 'disabled', false );
		} );
		return false;
	} );

	// Malware Scanner results details.
	$( document ).on( 'click', '.ss-details-ms', function() {
		var $this = $( this );
		var data = {
			action: 'sn_ss_ms_details',
			row_id: $this.attr( 'data-row-id' ),
			nonce: secninScheduledScanner.nonce
		};
		var timestamp = $this.attr( 'data-timestamp' );

		$( '.ss-details-ms' ).prop( 'disabled', true );
		$this.append( '<span class="spinner is-active"></span>' );

		$.post( ajaxurl, data, function( response ) {
			$( '.spinner' ).remove();
			$( '.ss-details-ms' ).prop( 'disabled', false );
			if ( ! response ) {
				SnDialog.alert({ message: secninScheduledScanner.strings.bad_ajax_response });
			} else {
				SnDialog.open({
					title: secninScheduledScanner.strings.dialog_title_ms.replace( '%s', timestamp ),
					bodyHtml: response,
					size: 'large'
				});
			}
		} ).fail( function() {
			SnDialog.alert({ message: secninScheduledScanner.strings.error_try_again });
			$( '.spinner' ).remove();
			$( '.ss-details-ms' ).prop( 'disabled', false );
		} );
		return false;
	} );

} );
