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

  // Initiate the Extension menu
  $( '#mainwp-vulnerability-checker-menu .item' ).tab();

  // Close modal and reload screen after
  $( '.close-reload-modal' ).on( 'click', function() {
    jQuery('#mainwp-vulnerability-checker-modal').modal( 'hide' );
    window.location.reload();
  });

  // Trigger the recheck action for a specific site
  $( '.vulner_action_recheck' ).on( 'click', function () {
    var obj = $( this ).closest( 'tr' );
    mainwp_vulner_results_recheck_start_specific( obj, false, false );
    return false;
  });

  // Filter groups
  $( '#vulner_btn_display' ).live( 'click', function () {
    $( this ).closest( 'form' ).submit();
  });

  // Trigger the recheck process for all sites
  $( '#vulner_recheck_all_sites' ).on('click', function () {

    var data = {
  		action: 'mainwp_vulner_load_sites',
      nonce: mainwp_vulner_loca.nonce,
      what: 'recheck'
	  };

    var statusEl = jQuery( '#mainwp-message-zone' );

    statusEl.html( '' ).hide();
    statusEl.removeClass( 'red green' );
    statusEl.html( 'Rechecking sites. Please wait...' ).show();

  	jQuery.post( ajaxurl, data, function (response) {
  		statusEl.html( '' );
      if ( response ) {
        if ( response['error'] ) {
          statusEl.addClass( 'red' );
          statusEl.html( response['error'] );
        } else if ( response['result'] ) {
          statusEl.html( '' ).hide();
          statusEl.removeClass( 'red green' );
          jQuery('#mainwp-vulnerability-checker-modal').find( '.content' ).html( response['result'] );
          jQuery('#mainwp-vulnerability-checker-modal').modal( 'show' );
          vulner_bulkTotalThreads = jQuery('.siteItemProcess[status=queue]').length;
          mainwp_vulner_recheck_all_sites_start_next();
        } else {
          statusEl.addClass( 'red' );
          statusEl.html( 'Undefined error. Please try again.' );
        }
      } else {
        statusEl.addClass( 'red' );
        statusEl.html( 'Undefined error. Please try again.' );
      }

  	}, 'json');

	  return false;
  });


  // Trigger bulk actions
  $( '#vulner_results_doaction_btn' ).on( 'click', function () {
    var bulk_act = $( '#vulner_results_action' ).find( '.item.selected' ).attr( 'value' );
    mainwp_vulner_results_do_bulk_action( bulk_act );
  });

  // Recheck on the Individual Vulnerabilities page
  $( '#vulner_recheck_site' ).on( 'click', function () {
    var button = this;
    var site_id = $( button ).attr( 'website-id' );

  	var data = {
  		action: 'mainwp_vulner_result_recheck',
  		websiteId: site_id,
  		force: 0,
      nonce: mainwp_vulner_loca.nonce
  	}

    $( button ).attr( 'disabled', 'disabled' );

    var statusEl = jQuery( '#mainwp-message-zone' );

    statusEl.html('');
    statusEl.removeClass( 'red green' );
    statusEl.html( '<i class="notched circle loading icon"></i> ' + __( 'Rechecking. Please wait...' ) ).show();

    jQuery.post(ajaxurl, data, function (response) {
      $(button).removeAttr( 'disabled' );
		  statusEl.html( '' );
      if ( response ) {
        if ( response['error'] ) {
          statusEl.addClass( 'red' );
          statusEl.html( response['error'] );
        } else if (response['ok']) {
          statusEl.addClass( 'green' );
          statusEl.html( '<i class="close icon"></i>' + __( "Rechecked successfully!" ) );
          window.location = "admin.php?page=ManageSitesVulnerabilities&id=" + site_id;
        } else {
          statusEl.addClass( 'red' );
          statusEl.html( '<i class="close icon"></i>' + __( 'Undefined error. Please try again.' ) );
        }
      } else {
        statusEl.addClass( 'red' );
        statusEl.html( '<i class="close icon"></i>' + __( 'Undefined error. Please try again.' ) );
      }
	  }, 'json');
	return false;
  });

  // Trigger the Update/Delete action on indivisual site page
  $( 'a.vulner-detail-action-btn' ).on( 'click', function () {
    mainwp_vulner_upgrade_delete_plugintheme( $( this ) );
    return false;
  });
});

var vulner_bulkMaxThreads = 3;
var vulner_bulkTotalThreads = 0;
var vulner_bulkCurrentThreads = 0;
var vulner_bulkFinishedThreads = 0;

// Bulk action selection Force or Not to force
mainwp_vulner_results_do_bulk_action = function (act) {
  jQuery( '#mainwp-vulnerabilities-list tr' ).addClass( 'queue' );
	switch ( act ) {
    case 'recheck':
      mainwp_vulner_results_recheck_start_next( false );
      break;
    case 'force-recheck':
      mainwp_vulner_results_recheck_start_next( true );
      break;
	}
}

// Loop trugh the selected sites
mainwp_vulner_results_recheck_start_next = function ( force ) {
  var selector = '#mainwp-vulnerabilities-list tr';
  while ( ( objProcess = jQuery( selector + '.queue:first' ) ) && ( objProcess.length > 0 ) && ( vulner_bulkCurrentThreads < vulner_bulkMaxThreads ) ) {
    objProcess.removeClass( 'queue' );
    if ( objProcess.find( 'td input[type="checkbox"]:checked' ).length == 0 )
      continue;
    mainwp_vulner_results_recheck_start_specific( objProcess, true, force );
  }
}

// Recheck a specific site
mainwp_vulner_results_recheck_start_specific = function ( pObj, bulk, force ) {

  var statusEl = pObj

	var data = {
		action: 'mainwp_vulner_result_recheck',
		websiteId: pObj.attr( 'website-id' ),
		force: force ? 1 : 0,
    nonce: mainwp_vulner_loca.nonce
	}

	if ( bulk ) {
    vulner_bulkCurrentThreads++;
  }

  statusEl.html( '<td colspan="9"><i class="notched circle loading icon"></i> ' + __( 'Rechecking. Please wait...' ) + '</td>' );
	jQuery.post( ajaxurl, data, function (response) {
		statusEl.html( '<td colspan="9"><i class="times circle red icon"></i> ' + __( '' ) + '</td>' );
		pObj.removeClass( 'queue' );
    if ( response ) {
      if ( response['error'] ) {
        statusEl.html( '<td colspan="9">' + response['error'] + '</td>' );
      } else if ( response['ok'] ) {
        statusEl.html( '<td colspan="9"><i class="check circle green icon"></i> ' + __( 'Checked successfully!' ) + '</td>' );
      } else {
        statusEl.html( '<td colspan="9"><i class="times circle red icon"></i> ' + __( 'Undefined error. Please try again.' ) + '</td>' );
      }
    } else {
      statusEl.html( '<td colspan="9"><i class="times circle red icon"></i> ' + __( 'Undefined error. Please try again.' ) + '</td>' );
    }

    if ( !bulk ) {
      window.location.reload();
    }

		if ( bulk ) {
      vulner_bulkCurrentThreads--;
      vulner_bulkFinishedThreads++;
      mainwp_vulner_results_recheck_start_next( force );
		}

    if ( vulner_bulkCurrentThreads == 0 ) {
      window.location.reload();
    }

	}, 'json');

	return false;
}

// Loop throug all sites
mainwp_vulner_recheck_all_sites_start_next = function () {
  while ( ( objProcess = jQuery( '.item[status=queue]:first' ) ) && ( objProcess.length > 0 ) && ( vulner_bulkCurrentThreads < vulner_bulkMaxThreads ) ) {
    objProcess.attr( 'status', 'processed' );
    mainwp_vulner_recheck_all_sites_start_specific( objProcess );
  }
}

// Check all sites
mainwp_vulner_recheck_all_sites_start_specific = function (pObj) {

	var statusEl = objProcess.find( '.status' );

	vulner_bulkCurrentThreads++;

	var data = {
		action: 'mainwp_vulner_result_recheck',
		websiteId: pObj.attr( 'website-id' ),
    nonce: mainwp_vulner_loca.nonce
	};

  statusEl.html( '' );
	statusEl.html( '<i class="notched circle loading icon"></i> ' + 'Checking...' );

	jQuery.post( ajaxurl, data, function ( response ) {
    if ( response) {
      if ( response.error ) {
        statusEl.html( '<i class="circle times red icon"></i> ' + response.error );
      } else if ( response.ok ) {
        statusEl.html( '<i class="circle check green icon"></i> ' + __( 'Checked successfully!' ) );
      } else {
        statusEl.html( '<i class="circle times red icon"></i> ' + __( 'Undefined error. Please try again.' ) );
      }
    } else {
      statusEl.html( '<i class="circle times red icon"></i> ' + __( 'Undefined error. Please try again.' ) );
    }

		vulner_bulkCurrentThreads--;
		vulner_bulkFinishedThreads++;
		mainwp_vulner_recheck_all_sites_start_next();
	}, 'json' );
	return false;
}

// Update/Delete vulnerable instances
mainwp_vulner_upgrade_delete_plugintheme = function (pObj) {
  var action = pObj.attr( 'what' );
	var parent = pObj.closest( '.vulner-detail-actions' );
	var type   = parent.attr( 'action-type' );
  var slug   = parent.attr( 'slug' );

  if ( action == 'delete' ) {
    if ( !confirm( __( 'Are you sure?' ) ) ) {
      return false;
    }
  }

  var data = false;

  if ( action == 'update' ) {
    data = {
      action: 'mainwp_vulner_upgrade_plugintheme',
      websiteId: parent.attr( 'website-id' ),
      type: type,
      'slugs[]': [slug],
      nonce: mainwp_vulner_loca.nonce
    }
	} else if ( action == 'delete' ) {
    if (type == 'plugin') {
      data = {
        action: 'mainwp_vulner_delete_plugin',
        websiteId: parent.attr( 'website-id' ),
        plugins: [slug],
        nonce: mainwp_vulner_loca.nonce
      }
    } else {
      var name = parent.attr( 'theme-name' ),
      data = {
        action: 'mainwp_vulner_delete_theme',
        websiteId: parent.attr( 'website-id' ),
        themes: [name],
        nonce: mainwp_vulner_loca.nonce
      }
    }
  }

  parent.find( '.vulner-detail-action-btn' ).each(function(){
    jQuery( this ).attr( 'disabled', 'disabled' );
  });

	statusEl = jQuery( '#mainwp-message-zone' );

  statusEl.html( '' );
  statusEl.removeClass( 'red green' );
  statusEl.html( '<i class="notched circle loading icon"></i> ' + __( 'Action in progress. Please wait...') ).show();

	jQuery.post(ajaxurl, data, function (response) {
		statusEl.html( '' );
    if ( response ) {
      if ( response['error'] ) {
        if ( response['error'] == 'IsActivatedTheme' ) {
          statusEl.html( '<i class="close icon"></i> ' +  __( 'Active theme could not be deleted. Please deactivate the theme first.' ) );
          statusEl.addClass( 'red' );
        } else {
          statusEl.html( '<i class="close icon"></i> ' + response['error'] );
          statusEl.addClass( 'red' );
        }
      } else if ( (action == 'delete' && response['result'] ) || ( action == 'update' && response['upgrades'][slug] ) ) {
        statusEl.html( '<i class="close icon"></i> ' + __( 'Action completed successfully!' ) );
        statusEl.addClass( 'green' );
        scrollToElement();
        jQuery( '#vulner_recheck_site' ).trigger( "click" );
      } else {
        statusEl.html( '<i class="close icon"></i> ' + __( "Undefined error" ) );
        statusEl.addClass( 'red' );
      }
    } else {
      statusEl.html( '<i class="close icon"></i> ' + __( "Undefined error" ) );
      statusEl.addClass( 'red' );
    }
	}, 'json');
	return false;
}
