$( document ).ready(function() {

	let buttonContent = '<i class="fas fa-file-import"></i>'+af2_import_object.strings.import;
	let buttonContentLoad = '<span class="af2_hide loading">&nbsp;<i class="fas fa-circle-notch fa-spin"></i></span>';

    $(document).on('click', '#af2_export', _ => {
        $.ajax({
            url: af2_menu_components_object.ajax_url,
            type: "POST",
            data: { action: 'af2_export' },
            success: (resp) => { window.location.href = JSON.parse(resp).file; },
            error: () => { }
        });
    });
    
    $('#af2_import').on('submit', function(e) {
		e.preventDefault();
		if(!$('#af2_import_button').hasClass('af2_btn_disabled')) {
			const formData = new FormData( $(this)[0] );
			formData.append('action', 'af2_import');
			$('#af2_import_button').prop('disabled', true);
			$('#af2_import_button').addClass('af2_btn_disabled');


			$('form[name="af2_import_form"] #af2_import_button').html(buttonContent+' - '+af2_import_object.strings.wait+buttonContentLoad);
			$('form[name="af2_import_form"] #af2_import_button .loading').removeClass('af2_hide');


			fetch( af2_menu_components_object.ajax_url, {
				method: 'POST',
				body: formData
			} )
			.then( x => x.json() )
			.then( r => { 
				$('#af2_import_button').removeAttr('disabled'); 
				$('#af2_import_button').removeClass('af2_btn_disabled'); 
				$('form[name="af2_import_form"] #af2_import_button .loading').addClass('af2_hide');
				$('#af2_import_button').html(af2_import_object.strings.success); 
				$('#af2_import_button').addClass('af2_succeed_import'); 

				setTimeout(_ => {
					window.location.reload();
				}, 1000);
			});
		}
	});


	$('#af2_import_upload').on('change', _ => {
		$('#af2_import_upload_label').html($('#af2_import_upload_label').data('selectedlabel'));
		$('#af2_import_button').removeClass('af2_btn_disabled');
		$('#af2_import_button').removeAttr('disabled');
	});

});