define(['jquery'], function($){
	return function(){
		this.saved_entry_deleted = false;

		var integration_count = 0;

		this.add_entry = function(event){
			event.preventDefault();

            integration_count += 1;

			var template = '	<div class="api-form entry-container mb-2">\n' +
			' 		<div class="form-row"><input type="hidden" name="entry_status[]" class="entry-status-field" value="new">' +
			'				<label for="entry_keys[]_'+ integration_count  +'" class="col-form-label col-12 col-sm-2">' + lmsg('admin.integration.entry_key') + '</label>\n' +
			'				<input type="text" id="entry_keys[]_'+ integration_count  +'" name="entry_keys[]" class="form-control col-12 col-sm-3" value="">\n' +

			'				<label for="entry_values[]_'+ integration_count  +'" class="col-form-label col-12 col-sm-2">' + lmsg('admin.integration.entry_value') + '</label>\n' +
			'				<input type="text" id="entry_values[]_'+ integration_count  +'" name="entry_values[]" class="form-control col-12 col-sm-3" value="">\n' +
			'			    <div class="col-12 col-sm-2 my-1 my-sm-0 pl-0 pl-sm-1"><a href="#" class="btn btn-danger" onclick="window.integration.remove_entry(event);" rel="tooltip" title="' + lmsg('admin.integration.delete_entry') + '" data-saved="0"><ion-icon name="trash-outline"></ion-icon></a></div>\n' +
			'			</div><hr>';

			$('#entry_set_container').append(template);
			this.showHideDeleteButtons();
		};

		this.remove_entry = function(event){
			event.preventDefault();
			var t = event.target;
			var is_saved = null;
			// the target might be the button itself or the span within it, so need to account for this
			if (t.tagName == 'SPAN')
			{
				is_saved = $(t).parent().attr('data-saved');
				$(t).parent().tooltip('dispose');
			}
			else
			{
				is_saved = $(t).attr('data-saved');
				$(t).tooltip('dispose');
			}
			$(t).closest('.entry-container').remove();
			this.showHideDeleteButtons();
			// only show the save warning/confirmation if a deleted entry has already been saved at some point in the past
			if (is_saved === '1')
			{
				this.saved_entry_deleted = true;
			}
		};

		this.edit_entry = function(event)
		{
			event.preventDefault();
			var container = $(event.target).closest('.entry-container');
			container.find('.masked-value-display').hide();
			container.find('.existing-key-display').hide();
			container.find('.value-edit-field').show();
			container.find('.key-edit-field').show();
			container.find('.entry-status-field').val('changed');
		};

		this.showHideDeleteButtons = function()
		{
			var entry_containers = $('.entry-container');
			if (entry_containers.length == 1)
			{
				// remove the delete button if there is only one entry
				$(entry_containers[0]).find('.entry-delete-button').hide();
			}
			else
			{
				entry_containers.each(function(idx, elem){
					$(elem).find('.entry-delete-button').show();
				});
			}
		}

	}
});
