---
# front matter in order to pull in the api endpoint from config
---


function getQueryStrings() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

$( document ).ready(function(){
    $('body').removeClass('is-preload');

    // Check if query strings were passed to automatically show the secret
    let token = getQueryStrings()['token'];
    if ( token ) {
      showSecret(token);
      $('#retrieve-secret').hide();
    }
});

$('#create-secret').on('submit', function(event) {
	event.stopPropagation();
	event.preventDefault();
	window.setTimeout(function() {

		var data = {
			username: $('#secret-username').val(),
			password: $('#secret-password').val(),
			message: $('#secret-message').val(),
			expiration: $('#secret-expiration').val(),
			expire_on_read: $('#secret-expire-on-read')[0].checked
		}

		$.ajax({
			method: 'POST',
			url: '{{ site.secret_endpoint }}',
			crossDomain: 'true',
			contentType: 'application/json',
			data: JSON.stringify(data),
			success: function (res){
        let url = '{{ site.url }}{{ site.baseurl }}/retrieve/index.html?token=' + res['token']
				$('#create-secret').trigger('reset');
				$('#secret-response').html('<a href="' + url + '">' + url + '</a>');
				$('#secret-response').removeClass('hidden');
			},
			error: function (res){
				$('#secret-response').html('Something went wrong: ' + JSON.stringify(res.responseJSON));
				$('#secret-response').removeClass('hidden');
			}
		});
	}, 750);
});


function showSecret(token) {
  $.ajax({
    method: 'GET',
    url: '{{ site.secret_endpoint }}?token=' + token,
    crossDomain: 'true',
    contentType: 'application/json',
    success: function (res){
      $('#retrieve-secret').trigger('reset');
      $('#secret-response').removeClass('hidden');
      $('#response-username').html(res['username']);
      $('#response-password').html(res['password']);
      $('#response-message').html(res['message']);
      $('#response-expiration').html(res['expiration']);
    },
    error: function (res){
      $('#secret-response').html('Something went wrong: ' + JSON.stringify(res.responseJSON));
      $('#secret-response').removeClass('hidden');
    }
  })
}


$('#retrieve-secret').on('submit', function(event) {
	event.stopPropagation();
	event.preventDefault();
	window.setTimeout(function() {
    var token = $('#secret-token').val();
		showSecret(token);
	}, 750);
});
