/**
 * Input validation
 * 
 * @category    Utilities
 * @package     ATProcessor
 * @author      Sam Meredith <sam@aandtinstruments.com>
 * @version     0.1
 */

const maxInactiveTime_ms = 600000;	///!< Boards/Displays persist on webpage for 10 mins after last contact

/**
 * Check for a valid netmask.
 */
validateNetmask = function( $input ) {
	let valid = true;
	let digits = $input.val().split('.');

	if (digits.length !== 4) {
		valid = false
	} else {
		for (let digit of digits) {
			if (!["255", "254", "252", "248", "240", "224", "192", "128", "0"].includes(digit)) {
				valid = false;
				break;
			}
		}
	}

	if (!valid) {
		$input.css('border-color', 'red').select().focus();
		$('#dialog-text').text('Invalid Netmask.');
		$('#dialog').dialog( {
			title: "Invalid Input"
		}).dialog('open');
	} else {
		$input.css('border-color', '');
	}

	return valid;
}

/**
 * Check for valid IP Address
 */
validateIPAddress = function( $input ) {
	let valid = true;

	if ( $input.val() == '' ) {
		valid = false;
	}

	let digits = $input.val().split('.');
	if ( digits.length !== 4 )
		valid = false;

	for (let i = 0; i < digits.length; i++) {
		if ( parseInt(digits[i]) < 0 || parseInt(digits[i]) > 255 )
			valid = false;
	}

	if (!valid) {
		$input.css('border-color', 'red').select().focus();
		$('#dialog-text').text('Invalid IP Address.')
		$('#dialog').dialog( {
			title: "Invalid Input"
		}).dialog('open');
	} else {
		$input.css('border-color', '');
	}

	return valid;
}

/**
 * $input should be a number rounded to decimalPlaces
 */
validateNumericInput = function( $input, decimalPlaces ) {
	
	//Set empty inputs to zero
	if ( $input.val() == '' ) {
		$input.val( parseFloat('0').toFixed(decimalPlaces) );
		return true;
	}

	var numericInput = parseFloat( $input.val() );
	if ( isNaN(numericInput) ) {
		$input.css('border-color', 'red').select().focus();
		$('#dialog-text').text('Input should be a number with zero or one decimal places.')
		$('#dialog').dialog( {
			title: "Invalid Input"
		}).dialog('open');
		return false;
	} else {
		$input.css('border-color', '').val(numericInput.toFixed(decimalPlaces));
	}
	
	return true;
	
}

/**
 * $input should be between minVal and maxVal, rounded to decimalPlaces
 */
validateRange = function( $input, decimalPlaces, minVal, maxVal, defaultVal ) {

	//Set empty inputs to default value
	if ( $input.val() == '' ) {
		$input.val( parseFloat(defaultVal).toFixed(decimalPlaces) );
		return true;
	}

	var numericInput = parseFloat( $input.val() );
	if ( isNaN(numericInput) ) {
		$input.css('border-color', 'red').select().focus();
		$('#dialog-text').text('Input should be a number with zero or one decimal places.')
		$('#dialog').dialog( {
			title: "Invalid Input"
		}).dialog('open');
		$input.val( parseFloat(defaultVal).toFixed(decimalPlaces) );
		return false;
	} else if ( numericInput < minVal || numericInput > maxVal ) {
        $input.css('border-color', 'red').select().focus();
		if (Number.MAX_SAFE_INTEGER - maxVal <= Number.EPSILON) {
			$('#dialog-text').text('Input should be greater than ' + minVal + '.');
		} else {
			$('#dialog-text').text('Input should be between ' + minVal + ' and ' + maxVal + '.');
		}
		$('#dialog').dialog( {
			title: "Invalid Input"
		}).dialog('open');
		var inputVal = (numericInput < minVal) ? minVal : maxVal;
		$input.val( inputVal.toFixed(decimalPlaces) );
		return false;
	} else {
		$input.css('border-color', '').val(numericInput.toFixed(decimalPlaces));
	}
	
	return true;
}

/**
 * Check string is a valid timestamp
 **/
validateTimestamp = function(timestamp) {
	 
	if ($.isNumeric(timestamp)) {
		return (new Date(parseInt(timestamp)).getTime() > 0);
	} else {
		return false;
	}
}


/**
 * Check for a valid Latitude input
 **/
validateLatitude = function( $lat_degrees, $lat_minutes, $lat_direction, storedLatObj )
{
	//Validate Lat-Long inputs
	var degrees = +$lat_degrees.val().trim();
	//Degrees should be between 0 and 90
	if (degrees < 0 || degrees > 90) {
		$('#dialog-text').text('Latitude expected in degrees and decimal minutes, e.g. 50 46.303 N');
		$('#dialog').dialog({
			title: 'Invalid Latitude'
		}).dialog("open");
		$lat_degrees.css('border-color', 'red');
		return false;
	} else { $lat_degrees.css('border-color', ''); }
	var minutes = +$lat_minutes.val().trim();
	//Minutes should be between 0 and 60
	if (minutes < 0 || minutes >= 60) {
		$('#dialog-text').text('Latitude expected in degrees and decimal minutes, e.g. 50 46.303 N');
		$('#dialog').dialog({
			title: 'Invalid Latitude'
		}).dialog("open");
		$lat_minutes.css('border-color', 'red');
		return false;
	} else { $lat_minutes.css('border-color', ''); }
	var decimalDegrees = degrees + (minutes / 60.0);
	if ( $lat_direction.find(":selected").val() == 'South') { decimalDegrees *= -1; }
	storedLatObj.value = decimalDegrees.toFixed(6);
	return true;
}

/**
 * Check for a valid Longitude input
 **/
 validateLongitude = function( $long_degrees, $long_minutes, $long_direction, storedLongObj ) {
	degrees = +$long_degrees.val().trim();
	//Degrees should be between 0 and 180
	if (degrees < 0 || degrees > 180) {
		$('#dialog-text').text('Longitude expected in degrees and decimal minutes, e.g. 123 45.303 E');
		$('#dialog').dialog({
			title: 'Invalid Longitude'
		}).dialog("open");
		$long_degrees.css('border-color', 'red');
		return false;
	} else { $long_degrees.css('border-color', ''); }
	minutes = +$long_minutes.val().trim();
	//Minutes should be between 0 and 60
	if (minutes < 0 || minutes >= 60) {
		$('#dialog-text').text('Longitude expected in degrees and decimal minutes, e.g. 123 45.303 E');
		$('#dialog').dialog({
			title: 'Invalid Longitude'
		}).dialog("open");
		$long_minutes.css('border-color', 'red');
		return false;
	} else { $long_minutes.css('border-color', ''); }
	decimalDegrees = degrees + (minutes / 60.0);
	if ($long_direction.find(":selected").val() == 'West') { decimalDegrees *= -1; }
	storedLongObj.value = decimalDegrees.toFixed(6);
	return true;
 }