<?php

  //  ini_set("display_errors", 1);
    include_once(PATH_TO_ROOT."/webcati/_plugins/takePhoto/class/class.takePhoto.plugin.php");
    $data = new TakePhoto($db);
    $data->load($projectId, $q->id);
   /*if(count($ansArr) > 0)
    {
        include(PATH_TO_ROOT."/webcati/_plugins/slider/web/slider.systemScale.php");
        exit;        
    }
    print "<pre>";
    var_dump($fieldsValues);
    var_dump($ansArr);
	var_dump($q->getStructureFields($q->odg_sql));
    print "</pre>";*/
   /* print "#############################################################################################################################################################";*/
   $ansId = $q->getStructureFields($q->odg_sql)[0];
?>

<?php
$html .= '<script src="' .PATH_TO_ROOT.'/webcati/_plugins/takePhoto/web/js/hermite.js"></script>';
$html .= '<select id="inputSelector' . $q->q_name .'"></select>
	<br><br>
	<video id="webcam' . $q->q_name .'" width="640" autoplay></video>
	<br>
	<canvas id="screenshot-canvas' . $q->q_name .'" style="display:none"></canvas>
	<br>
	<canvas id="canvas2' . $q->q_name .'" style="display: none"></canvas>
	<br>
	<button type="button" style="width: 480px; height: 50px; border-color: red; border-style: solid" id="screenshot-button' . $q->q_name .'">Slikaj</button>
	<br>
	<div id="prejsnjaSlikaDiv' . $q->q_name . '" style="display: none">
		<br>
		<span>Image:</span> &nbsp;
		<br>
		<img id="prejsnjaSlika'.$q->q_name.'" src=""/>
	</div>
	<br>
	<!--
	<span id="status" style="">Nisi nalozil slike!</span>
	-->
	';


$html .= '<input type="hidden" name="answers['. $q->getStructureFields($q->odg_sql)[0].']" value="" id="singlevar'. $q->q_name . '">';
//$html .= $fieldsValues[$ansId];	// S TEM LAHKO PRIKAŽEM TRENUTNO SLIKO IZ BAZE....
?>
        
<script>
$( document ).ready(function() {
	var cameraIDs;
	var video = document.querySelector('#webcam<?php echo $q->q_name; ?>');
	
	
	<?php
	if(!empty($fieldsValues[$ansId])) {
	?>
		$('#prejsnjaSlika<?php echo $q->q_name; ?>').attr("src", "<?php echo $fieldsValues[$ansId]; ?>");
		$('#prejsnjaSlikaDiv<?php echo $q->q_name; ?>').show();
		
	<?php
	}
	?>
	
	loadCamera<?php echo $q->q_name; ?>();
	
	function loadCamera<?php echo $q->q_name; ?>() {
		try {
			MediaStreamTrack.getSources(function(sourceInfos) {
				var foundBack = false;
				var videoSource = null;
				for (var i = 0, j=1; i != sourceInfos.length; ++i) {
					var sourceInfo = sourceInfos[i];
					if (sourceInfo.kind === 'video') {
						videoSource = sourceInfo.id;
						$("#inputSelector<?php echo $q->q_name; ?>").append($("<option></option>")
										 .attr("value", sourceInfo.id)
										 .text('camera ' + j));
						j++;
						
						if(sourceInfo.facing === 'environment') {	// prioriteta na zadnji kameri
							foundBack = true;
							$("#inputSelector<?php echo $q->q_name; ?>").val(sourceInfo.id);
							sourceSelected<?php echo $q->q_name; ?>(sourceInfo.id);
							//$("#status").html("back camera found!");
						}
					}
				}
				if(!foundBack) {
					$("#inputSelector<?php echo $q->q_name; ?>").val(sourceInfo.id);
					sourceSelected<?php echo $q->q_name; ?>(sourceInfo.id);
				}
			});
		} catch(err) {
			$("#inputSelector<?php echo $q->q_name; ?>").hide();
			sourceSelected<?php echo $q->q_name; ?>();
		}
	}
	$("#inputSelector<?php echo $q->q_name; ?>").change(function() {
		sourceSelected<?php echo $q->q_name; ?>($("#inputSelector<?php echo $q->q_name; ?>").val());
	});

	function sourceSelected<?php echo $q->q_name; ?>(videoSource) {
		navigator.getUserMedia = (navigator.getUserMedia ||
						navigator.webkitGetUserMedia ||
						navigator.mozGetUserMedia ||
						navigator.msGetUserMedia);
		if (navigator.getUserMedia) {
			if(navigator.stream)
				navigator.stream.stop();
			
			var constraints = {
				video: {
					optional: [{sourceId: videoSource}]
				},
				audio: false
			};
				
			startLiveView<?php echo $q->q_name; ?>(constraints);
		}
		else {
		  alert('Brskalnik ne podpira video zajemanja slike');
		}
		
	}
	
	function startLiveView<?php echo $q->q_name; ?>(constraints) {
		navigator.getUserMedia(constraints, function (localMediaStream) {
			navigator.stream = localMediaStream;
			video.src = window.URL.createObjectURL(localMediaStream);
		}, onFailure);
	}
	
	function onFailure(err) {
        alert("NAPAKA: " + err.name);
    }
	
	var canvas = document.querySelector('#screenshot-canvas<?php echo $q->q_name; ?>');
	var ctx = canvas.getContext('2d');
	 
	$('#screenshot-button<?php echo $q->q_name; ?>').click(function() {
		snapshot<?php echo $q->q_name; ?>();
	});
	 
	function snapshot<?php echo $q->q_name; ?>() {
		$('#screenshot-button<?php echo $q->q_name; ?>').hide();
		canvas.width = video.videoWidth;
		canvas.height = video.videoHeight;
		ctx.drawImage(video, 0, 0);
		try {
			naloziNaServer<?php echo $q->q_name; ?>();
		}
		catch(err) {
			$('#screenshot-button<?php echo $q->q_name; ?>').show();
			loadCamera<?php echo $q->q_name; ?>()
		}
	}
	
	function naloziNaServer<?php echo $q->q_name; ?>(){
		
		var data = ctx.getImageData(0, 0, canvas.width, canvas.height);
		// store the current globalCompositeOperation
		var compositeOperation = ctx.globalCompositeOperation;
		// set to draw behind current content
		ctx.globalCompositeOperation = "destination-over";
		//set background color
		ctx.fillStyle = "#FFFFFF";
		// draw background/rectangle on entire canvas
		ctx.fillRect(0,0,canvas.width, canvas.height);

		var tempCanvas = document.querySelector('#canvas2<?php echo $q->q_name; ?>'),
		tCtx = tempCanvas.getContext("2d");
		
		orgW = canvas.width;
		orgH = canvas.height;
		
		var zeljenW = <?php echo $data->getVal('max_width'); ?>;
		var zeljenH = <?php echo $data->getVal('max_height'); ?>;
		
		var faktorPomanjsanja;
		
		if(orgW > zeljenW)
			faktorPomanjsanja = orgW / zeljenW;
		else if(orgH > zeljenH)
			faktorPomanjsanja = orgH / zeljenH;
			

		tempCanvas.width = orgW / faktorPomanjsanja;
		tempCanvas.height = orgH / faktorPomanjsanja;

		if(canvas.width > 0 && canvas.height > 0) {
			if(zeljenW < orgW || zeljenH < orgH) {
				resample_hermite(canvas, canvas.width, canvas.height, tempCanvas.width, tempCanvas.height)
				tCtx.drawImage(canvas,0,0);
				var img = tempCanvas.toDataURL("image/jpeg", <?php echo $data->getVal('image_quality'); ?>);
				saveToDisk<?php echo $q->q_name; ?>(img);
			} else {
				var img = canvas.toDataURL("image/jpeg", <?php echo $data->getVal('image_quality'); ?>);
				saveToDisk<?php echo $q->q_name; ?>(img);
			}
		} else {
			
			$('#screenshot-button<?php echo $q->q_name; ?>').show();
			//$('#status<?php echo $q->q_name; ?>').html("NAPAKA: Velikost slike je 0!");
		}
	}
	
	function saveToDisk<?php echo $q->q_name; ?>(image) {
		$('#screenshot-button<?php echo $q->q_name; ?>').show();
		$('#singlevar<?php echo $q->q_name; ?>').attr("value", image);
		$('#prejsnjaSlika<?php echo $q->q_name; ?>').attr("src", image);
		$('#prejsnjaSlikaDiv<?php echo $q->q_name; ?>').show();
	}
});
</script>
<?php
 if ($q->must_answer)
 {
     if(strlen($_SESSION['mustAnswerCondition']) > 0) 
        $_SESSION['mustAnswerCondition'] .= ' AND strlen($' .  $q->getStructureFields($q->odg_sql)[0] .') > 0';
		
    else
        $_SESSION['mustAnswerCondition'] .= ' strlen($' .  $q->getStructureFields($q->odg_sql)[0] .') > 0';
 }
?>