// Generated by CoffeeScript 1.12.8

/*
LemonLDAP::NG 2F registration script
 */

(function() {
  var delete2F, displayError, setMsg;

  setMsg = function(msg, level) {
    $('#msg').attr('trspan', msg);
    $('#msg').html(window.translate(msg));
    $('#color').removeClass('message-positive message-warning alert-success alert-warning');
    $('#color').addClass("message-" + level);
    if (level === 'positive') {
      level = 'success';
    }
    $('#color').addClass("alert-" + level);
    return $('#color').attr("role", "status");
  };

  displayError = function(j, status, err) {
    var res;
    console.log('Error', err);
    res = JSON.parse(j.responseText);
    if (res && res.error) {
      res = res.error.replace(/.* /, '');
      console.log('Returned error', res);
      if (res.match(/module/)) {
        return setMsg('notAuthorized', 'warning');
      } else {
        return setMsg(res, 'warning');
      }
    }
  };

  delete2F = function(device, epoch, prefix) {
    if (!prefix) {
      if (device === 'U2F') {
        prefix = 'u';
      } else if (device === 'UBK') {
        prefix = 'yubikey';
      } else if (device === 'TOTP') {
        prefix = 'totp';
      } else if (device === 'WebAuthn') {
        prefix = 'webauthn';
      } else {
        prefix = device.toLowerCase();
      }
    }
    return $.ajax({
      type: "POST",
      url: portal + "2fregisters/" + prefix + "/delete",
      data: {
        epoch: epoch
      },
      dataType: 'json',
      error: displayError,
      success: function(resp) {
        var e;
        if (resp.error) {
          if (resp.error.match(/notAuthorized/)) {
            return setMsg('notAuthorized', 'warning');
          } else {
            return setMsg('unknownAction', 'warning');
          }
        } else if (resp.result) {
          $("#delete-" + epoch).hide();
          e = jQuery.Event("mfaDeleted");
          $(document).trigger(e, [
            {
              "type": device,
              "epoch": epoch
            }
          ]);
          if (!e.isDefaultPrevented()) {
            return setMsg('yourKeyIsUnregistered', 'positive');
          }
        }
      },
      error: displayError
    });
  };

  $(document).ready(function() {
    $('body').on('click', '.remove2f', function() {
      return delete2F($(this).attr('device'), $(this).attr('epoch'), $(this).attr('prefix'));
    });
    $('#goback').attr('href', portal);
    return $(".data-epoch").each(function() {
      var myDate;
      myDate = new Date($(this).text() * 1000);
      return $(this).text(myDate.toLocaleString());
    });
  });

}).call(this);
