/* globals jQuery:true, ajaxurl:true, wf_sn_af:true */
/*
 * Security Ninja - Auto Fixer add-on
 * (c) 2014. Web factory Ltd
 */


 jQuery(document).ready(function($) {
  if (typeof wf_sn_af === 'undefined') {
    return;
  }

  function getFixMessage(response) {
    if (!response || !response.data) {
      return '';
    }
    if (typeof response.data === 'string') {
      return response.data;
    }
    if (response.data.message) {
      return response.data.message;
    }
    return '';
  }

  function rerunSingleTest(test_id, onComplete) {
    var nonce = wf_sn_af.nonce_run_tests;
    if (!nonce) {
      if (typeof onComplete === 'function') {
        onComplete(null);
      }
      return;
    }

    $.ajax({
      type: 'POST',
      url: ajaxurl,
      data: {
        action: 'sn_run_single_test',
        _ajax_nonce: nonce,
        testarr: [test_id],
        stepid: 0
      },
      dataType: 'json',
      success: function (response) {
        if (response && response.success && response.data && typeof window.wfSnUpdateTestRow === 'function') {
          window.wfSnUpdateTestRow(test_id, response.data);
        }
        if (typeof onComplete === 'function') {
          onComplete(response);
        }
      },
      error: function () {
        if (typeof window.wfSnClearTestSpinners === 'function') {
          window.wfSnClearTestSpinners(test_id);
        }
        if (typeof onComplete === 'function') {
          onComplete(null);
        }
      }
    });
  }

  function showFixResult(test_id, fixMessage, rerunResponse) {
    var strings = wf_sn_af.strings || {};
    var statusNote = '';
    if (rerunResponse && rerunResponse.data) {
      if (parseInt(rerunResponse.data.status, 10) === 10) {
        statusNote = strings.fix_rerun_passed || 'The test was re-run and now passes.';
      } else {
        statusNote = strings.fix_rerun_not_passed || 'The fix was applied, but the test still does not pass.';
      }
    } else {
      statusNote = strings.fix_rerun_failed || 'Re-run the test manually to refresh the status and score.';
    }

    var html = '<div class="notice notice-success inline"><p><strong>' + (strings.fix_applied || 'Fix applied.') + '</strong> ' +
      fixMessage + '</p><p>' + statusNote + '</p></div>';

    jQuery(".snautofix[data-test-id='" + test_id + "']").html(html).show();
  }

  $(document).on('click', '.sn_af_run_fix', function(e) {
    e.preventDefault();
    var test_id = jQuery(this).data('test-id');
    var $button = jQuery(this);

    var strings = wf_sn_af.strings || {};
    SnDialog.confirm({
      message: strings.confirm_apply_fix || 'Are you sure you want to apply the fix?'
    }).then(function(ok) {
      if (!ok) {
        return;
      }

    $button.prop('disabled', true);
    jQuery(".snautofix[data-test-id='" + test_id + "']").html('<div class="sn-fixer-loader">' + (strings.applying_fix || 'Applying the fix…') + '</div>').show();

    var fix_fields = {};

    jQuery(".snautofix[data-test-id='" + test_id + "'] input").each(function() {
      if ($(this).attr('type') === 'checkbox') {
        if ($(this).is(':checked')) {
          fix_fields[$(this).attr('name')] = 'true';
        } else {
          fix_fields[$(this).attr('name')] = 'false';
        }
      } else {
        fix_fields[$(this).attr('name')] = $(this).val();
      }
    });

    $.ajax({
      url: ajaxurl,
      type: 'POST',
      dataType: 'json',
      timeout: 120000,
      data: {
        action: 'sn_af_do_fix',
        _ajax_nonce: wf_sn_af.nonce_do_fix,
        test_id: test_id,
        fields: JSON.stringify(fix_fields)
      },
      success: function(response) {
        if (!response || !response.success) {
          var errMsg = (response && response.data && response.data.message) ? response.data.message : (strings.fix_failed || 'The fix could not be applied.');
          jQuery(".snautofix[data-test-id='" + test_id + "']").html('<p>' + errMsg + '</p>');
          $button.prop('disabled', false);
          return;
        }

        var fixMessage = getFixMessage(response);
        if (typeof window.wfSnClearTestSpinners === 'function') {
          window.wfSnClearTestSpinners(test_id);
        }

        rerunSingleTest(test_id, function (rerunResponse) {
          showFixResult(test_id, fixMessage, rerunResponse);
        });
      },
      error: function(xhr, status) {
        if (typeof window.wfSnClearTestSpinners === 'function') {
          window.wfSnClearTestSpinners(test_id);
        }
        var errText;
        if (status === 'timeout') {
          errText = strings.fix_timeout || 'The fix is still running or timed out. If the site prefix changed, re-run the test before trying again.';
        } else {
          errText = (xhr && xhr.responseJSON && xhr.responseJSON.data) ? xhr.responseJSON.data : (strings.fix_failed || 'The fix could not be applied.');
        }
        jQuery(".snautofix[data-test-id='" + test_id + "']").html('<p>' + errText + '</p>');
        $button.prop('disabled', false);
      }
    });
    });
  });



  // Listens for click on "Details" on tests page, that trigger an action here
  $(document).on('sn_test_details_dialog_open', function(e, test_id, test_status) {
    data = {
      'action': 'sn_af_get_fix_info',
      '_ajax_nonce': wf_sn_af.nonce_get_fix_info,
      'test_id': test_id,
      'test_status': test_status
    };

    // Only process failed tests or with warnings
    if ( test_status < 10) {
      $.get(ajaxurl, data, function(response) {
        jQuery('.tdesc-test-id-' + test_id + ' .spinner').remove();
        jQuery('.' + test_id + '.testtimedetails .spinner').remove();

        if (response.success) {
          content = response.data;
        } else {
          content = (wf_sn_af.strings && wf_sn_af.strings.fix_info_error) ? wf_sn_af.strings.fix_info_error : 'Unable to get fix info. Please reload the page and try again.';
        }

        jQuery( '.testtimedetails.' + test_id + ' .snautofix').html( content ).show();
      });
    }


  });




});
