function important_field_missing_alert(cssSelector) {
    if(
		jQuery( cssSelector ).attr('data-saved-value') == '' || 
	   	jQuery( cssSelector ).attr('data-saved-value') == '{"name":"- SELECT -","amazon_domain":"","pa_endpoint":"","region":""}' 
	) {
        	jQuery( cssSelector ).addClass( 'missing_value' );		   
    }
    jQuery( '.tr').removeClass( 'missing_value_row' );
	
    jQuery( '.tr:not(.legacy).api_group[data-saved-value=""]').addClass( 'missing_value_row' );
}

function consoleNewLine() {
	jQuery('#test_api_result').append('<br><br>');
}

function test_api(e) {
    jQuery('#test_api_result').html("Connecting...");
	
	let mode = e.target.id;
	let getItemsMode = (mode=='test_api_getitems');
	let searchItemsMode = (mode=='test_api' || mode=='test_api_searchitems')
	
	let getitems_asin;
	getitems_asin = jQuery('#test_api_getitems_asin').val();
	
	let searchitems_search;	
	searchitems_search = jQuery('#test_api_searchitems_search').val();
	
	if(getItemsMode) {
		if(getitems_asin.length != 10 || getitems_asin.search(/^[a-zA-Z0-9]+$/) == -1) {
			jQuery('#test_api_result').html('<span style="color:red">Please insert a valid ASIN!</span>');
			return;
		}
		jQuery('#test_api_result').html('Performing a getItems call to the APIs to retrieve product '+getitems_asin+' data.<br><br>Connecting...');
	}
	
	if(searchItemsMode) {
		if(mode=='test_api_searchitems' && searchitems_search.length < 1 ) {
			jQuery('#test_api_result').html('<span style="color:red">Please insert a search keyword!</span>');
			return;
		}
		jQuery('#test_api_result').html('Performing a searchItems call to the APIs.<br><br>Connecting...');
	}
	
	jQuery.ajax(
		jQuery("main").attr( "data-ajax" ), {
			method : "POST",
			dataType : "json",
			data : {
                action: "test_api",
                nonce: jQuery("main").attr( "data-nonce" ),
				mode: mode,
				asin: getitems_asin,
				search: searchitems_search
			},
			success: function(response_base64_withindex) {

				/* response is an innocent JSON string, it is encoded in base64 because otherwise the escaping mechanism destroys it*/
				let response_base64 = atob(response_base64_withindex);
				console.log(response_base64);
				let response = response_base64.substring(response_base64.indexOf("#") + 1);
				let responseObject = JSON.parse(response);
				let responsePretty = JSON.stringify(responseObject, null, 2);
                if(response) {
					let errors = '"Errors":';
					let errorshtml = '&quot;Errors&quot;'
					let errorsColor = '';
					if(response.includes(errors) || response.includes(errorshtml)) {
						errorsColor = ' style="color:red;" ';
						consoleNewLine();					
						jQuery('#test_api_result').append('<span'+errorsColor+'>Bad news, APIs answered with an error!</span>');   
					}
					consoleNewLine();					
					jQuery('#test_api_result').append('<span'+errorsColor+'>The APIs answer:');					
					jQuery('#test_api_result').append('<pre'+errorsColor+'>'+responsePretty+'</pre>');
				}
			},
			error: function(response) {
				jQuery('#test_api_result').html('Performed a getItems call to the APIs to retrieve product '+getitems_asin+' data.');
				consoleNewLine();
                jQuery('#test_api_result').html('<span style="color:red;">Connection failed with these credentials!<br>(check for any typos)</span>');
			}
		}
	);
	
}

function test_api2(e) {
    jQuery('#test_api_result').html("Connecting...");
	
	let mode = e.target.id;
	let getItemsMode = (mode=='test_api2_getitems');
	let searchItemsMode = (mode=='test_api2' || mode=='test_api2_searchitems')
	
	let getitems_asin;
	getitems_asin = jQuery('#test_api2_getitems_asin').val();
	
	let searchitems_search;	
	searchitems_search = jQuery('#test_api2_searchitems_search').val();
	
	if(getItemsMode) {
		if(getitems_asin.length != 10 || getitems_asin.search(/^[a-zA-Z0-9]+$/) == -1) {
			jQuery('#test_api_result').html('<span style="color:red">Please insert a valid ASIN!</span>');
			return;
		}
		jQuery('#test_api_result').html('Attempting an API call with the new Creators APIs');
		jQuery('#test_api_result').append('Performing a getItems call to the APIs to retrieve product '+getitems_asin+' data.<br><br>Connecting...');
	}
	
	if(searchItemsMode) {
		if(mode=='test_api2_searchitems' && searchitems_search.length < 1 ) {
			jQuery('#test_api_result').html('<span style="color:red">Please insert a search keyword!</span>');
			return;
		}
		jQuery('#test_api_result').html('Performing a searchItems call to the APIs.<br><br>Connecting...');
	}
	

	jQuery.ajax(
		jQuery("main").attr( "data-ajax" ), {
			method : "POST",
			dataType : "json",
			data : {
                action: "test_api",
                nonce: jQuery("main").attr( "data-nonce" ),
				mode: mode,
				asin: getitems_asin,
				search: searchitems_search
			},
			success: function(response_base64_withindex) {

				/* response is an innocent JSON string, it is encoded in base64 because otherwise the escaping mechanism destroys it*/
				let response_base64 = atob(response_base64_withindex);
				console.log(response_base64);
				let response = response_base64.substring(response_base64.indexOf("#") + 1);
				let responseObject = JSON.parse(response);
				let responsePretty = JSON.stringify(responseObject, null, 2);
                if(response) {
					let errors = '"Errors":';
					let errorshtml = '&quot;Errors&quot;'
					let errorsColor = '';
					if(response.includes(errors) || response.includes(errorshtml)) {
						errorsColor = ' style="color:red;" ';
						consoleNewLine();					
						jQuery('#test_api_result').append('<span'+errorsColor+'>Bad news, APIs answered with an error!</span>');   
					}
					consoleNewLine();					
					jQuery('#test_api_result').append('<span'+errorsColor+'>The APIs answer:');					
					jQuery('#test_api_result').append('<pre'+errorsColor+'>'+responsePretty+'</pre>');
				}
			},
			error: function(response) {
				jQuery('#test_api_result').html('Performed a getItems call to the APIs to retrieve product '+getitems_asin+' data.');
				consoleNewLine();
                jQuery('#test_api_result').html('<span style="color:red;">Connection failed with these credentials!<br>(check for any typos)</span>');
			}
		}
	);
	
}

function force_new_token(e) {
    jQuery('#force_new_token').html("Please wait...");
	
	jQuery.ajax(
		jQuery("main").attr( "data-ajax" ), {
			method : "POST",
			dataType : "json",
			data : {
                action: "amazingaffiliates_api_force_new_token",
                nonce: jQuery("main").attr( "data-nonce" )
			},
			success: function(response) {
				console.log('success');
				console.log(response);
			},
			error: function(response) {				
				console.log('fail');
				console.log(response);
			}
		}
	);
	
	setTimeout(() => {
		location.reload();
	}, "2000");
	jQuery('#force_new_token').html("Refreshing page...");
	
}

jQuery(document).ready( function() {
    
    jQuery(".amazingaffiliates_tab").tabs();
	
    important_field_missing_alert();
//    important_field_missing_alert( 'select[name="amazingaffiliates_settings_api_country"]' );
//    important_field_missing_alert( 'input[name="amazingaffiliates_settings_api_partner_tag"]' );
//    important_field_missing_alert( 'input[name="amazingaffiliates_settings_api_accessKey2"]' );
//    important_field_missing_alert( 'input[name="amazingaffiliates_settings_api_secretKey2"]' );
    
    jQuery( "input" ).on( "click change keyup mouseup paste", function(e) {
		important_field_missing_alert();
//        important_field_missing_alert( 'select[name="amazingaffiliates_settings_api_country"]' );
//        important_field_missing_alert( 'input[name="amazingaffiliates_settings_api_partner_tag"]' );
//        important_field_missing_alert( 'input[name="amazingaffiliates_settings_api_accessKey2"]' );
//        important_field_missing_alert( 'input[name="amazingaffiliates_settings_api_secretKey2"]' );
    });
    
    jQuery("#test_api").click( function(e) {
        e.preventDefault();
        test_api(e);
    });
	
	jQuery("#test_api_getitems").click( function(e) {
        e.preventDefault();
        test_api(e);
    });
	
	jQuery("#test_api_searchitems").click( function(e) {
        e.preventDefault();
        test_api(e);
    });
	
	jQuery("#force_new_token").click( function(e) {
        e.preventDefault();
        force_new_token(e);
    });
	
	jQuery("#test_api2").click( function(e) {
        e.preventDefault();
        test_api2(e);
    });
	
	jQuery("#test_api2_searchitems").click( function(e) {
        e.preventDefault();
        test_api2(e);
    });
	
	jQuery("#test_api2_getitems").click( function(e) {
        e.preventDefault();
        test_api2(e);
    });
    
});