<?php
	$holdButtonDisabled = true;

	require_once "header.php";
	const SIDEBAR_ITEMS = SETTINGS_HEADER_ITEMS;
	const SIDEBAR_LINKS = SETTINGS_HEADER_LINKS;
	require_once "sidebar.php";
	
	$dataType = $_GET["FieldId"];
    if ($dataType == "CanDevices") $dataType = "CANbus";
?>

<div class="content-wrapper" id="debug" data-heading="Settings" data-subheading="Diagnostics">

	<div class="debug-top-row">
		<select id="debug-select">
			<option value="All">All</option>
			<option value="Analogue Board">Analogue Board</option>
			<option value="Damping">Damping</option>
			<option value="Expedition">Expedition</option>
			<option value="Fastnet">Fastnet</option>
			<option value="Main Interface Board">Main Interface Board</option>
			<option value="NMEA0183">NMEA0183</option>
			<option value="CanBus">CANbus</option>
			<option value="ATProcessor">Processor</option>
			<option value="Speed Board">Speed Board</option>
			<option value="Speed Depth Board">Speed Depth Board</option>
			<option value="Wind Board">Wind Board</option>
		</select>
		
		<a class="button small gray" id="reload-button">
			<div class="reload"></div>
		</a>
		
		<a class="button medium gray" id="iframe-clear" style="float:right">Clear Sentences</a>
	</div>

	<iframe id="field-frame" 
		src="<?php echo HOST . ":8080?FieldID=" . $_GET["FieldId"];?>">
	</iframe>
		
	<div class="box box-bottom flex-row" id="logging-row" hidden>
		<a class="button medium gray" id="logging-start" style="flex-basis:150px;
			margin-right:16px;" data-state="off">
			Begin Data Logging
		</a>
		<div class="flex-field" style="flex-grow:1">
			<div class="field-container" id="logging-field" title="Number of rows logged."
				data-field="<?php 
                    if ($dataType == "Fastnet") echo fieldEnum::Fastnet_LogRowCount;
                    else if ($dataType == "NMEA") echo fieldEnum::NMEA_LogRowCount;
                    else if ($dataType == "CANbus") echo fieldEnum::CAN_LogRowCount;
                    else echo "";
                    ?>"
				data-sender="<?php echo PROCESSOR_ID?>"
				data-instance="<?php echo PROCESSOR_INSTANCE?>">
				&nbsp;
			</div>
		</div>
		<a class="button medium gray" id="logging-export" style="flex-basis:150px;
			margin-right:16px;" download="">
			Export Data Log
		</a>
		<select id="logging-select">
			<option value="">Select Log</option>
			<?php	
				$directory = array_filter(scandir("logs/DataLogs"), function($file) {
					return !( substr($file, 0, 1) == '.' ); 
				});
				foreach ($directory as $index => $file) {
					if ( strpos($file, $dataType) !== false ) {
						echo '
							<option	value="' . $file . '">
								' . explode(".", $file)[0] . '
							</option>
						';
					}
				}
			?>
		</select>
	</div>
	
</div>

<script type="text/javascript" src="/js/moment.min.js"></script>
<script type="text/javascript" src="/js/polyfill.js"></script>
<script>
$(document).ready(function() {

	var pageHandler = new InputPageHandler('debug.php?FieldId=all-refresh', 'Debug');

	var fieldId = '<?php echo $dataType;?>';
	var queryString = '';
	switch (fieldId) {
		case 'all-refresh':
			$('#iframe-clear').hide();
			$('#logging-row').hide();
			break;
		case 'NMEA':
			$('#debug-select').hide();
			$('#logging-row').show();
			queryString = 'LogNMEAData';
			break;
		case 'Fastnet':
			$('#logging-row').show();
			queryString = 'LogFastnetData';
			$('#iframe-clear').hide();
			$('#debug-select').hide();
			break;
        case 'CANbus':
            $('#logging-row').show();
            queryString = 'LogN2kData';
            $('#iframe-clear').hide();
            $('#debug-select').hide();
            break;
		default:
			$('#iframe-clear').hide();
			$('#debug-select').hide();
			$('#logging-row').hide();
			break;
	}
	
	//Clear NMEA sentences
	$('#iframe-clear').click(function() {
		$.ajax( {
			url: 'helpers.php',
			type: 'POST',
			data: {action: 'queryProcessor', query: 'FieldId=NMEA&Clear=True'},
			success: function() {
				$('#field-frame').attr('src', function(i, val) { return val; });
			}
		});
	});
	
	//Refresh iframe
	$('#reload-button').click(function() {
		$('#field-frame').attr('src', function(i, val) { return val; });
	});
	
	//Filter senderId by select value
	$('#debug-select').change(function() {
		var selected = $(this).find(':selected').val();
		$('#field-frame').attr('src', 'http://' + window.location.hostname + ':8080?FieldId=all-refresh&SenderId=' + selected);
	});
	
	//Check if logging active
	var fieldString = 'FieldId=' + '<?php 
        if ($dataType == "Fastnet") echo fieldEnum::Fastnet_LogRowCount;
        else if ($dataType == "NMEA") echo fieldEnum::NMEA_LogRowCount;
        else if ($dataType == "CANbus") echo fieldEnum::CAN_LogRowCount;
        else echo "";?>' + '&SenderId=' + '<?php echo PROCESSOR_ID?>' + '&SenderInstance=' + '<?php echo PROCESSOR_INSTANCE?>';
	$.ajax({
		url: '/helpers.php',
		type: 'POST',
		data: {
			action: 'queryProcessor',
			query: fieldString
		},
		success: function(result) {
			if ( result.includes('Rows Logged') ) {
				$('#logging-start').text('End Data Logging');
			}
		}
	});
	
	//Start or stop logging
	$('#logging-start').click(function() {
		if ( $(this).attr('data-state') == "off" ) {
			$.ajax({
				url: '/helpers.php',
				type: 'POST',
				data: {
					action: 'queryProcessor',
					query: queryString + '=start'
				}
			});
			$(this).attr('data-state', 'on');
			$(this).text('End Data Logging');
		} else {
			$.ajax({
				url: '/helpers.php',
				type: 'POST',
				data: {
					action: 'queryProcessor',
					query: queryString + '=stop'
				},
				success: function() 
                {
                    let fileName = "Unknown_";
                    if (fieldId == "Fastnet") fileName = "FastnetLog_";
                    else if (fieldId == "NMEA") fileName = "NMEALog_";
                    else if (fieldId == "CANbus") fileName = "CANbusLog_";

					fileName += moment().format('DD[_]MM[_]YYYY');
					if ($('#logging-select option[value="' + fileName + '.log"]').length == 0) {
						$('#logging-select').append(
							'<option value="' + fileName + '.log">' + fileName + '</option>'
						);
					}	
				}
			});
			$(this).attr('data-state', 'off');
			$(this).text('Begin Data Logging');
		}
	});
	
	//Export data log
	$('#logging-select').change(function() {
		var fileString = "/logs/DataLogs/" + $(this).find(':selected').val();
		$('#logging-export').attr('href', fileString);
	});
	
});
</script>

<?php require_once "footer.php";?>