<script>

	import { createEventDispatcher } from 'svelte';
	import { readFileAsync } from './helpers';
	import Papa from './vendor/papaparse.min.js';

	let datafiles, imagefiles, isValid, fixation_data, sequential_fixation_data;
	const image = new Image();
	const dispatch = createEventDispatcher();

	$: isValid = datafiles && imagefiles && datafiles[0] && imagefiles[0];

	async function visualize() {

		image.src = await readFileAsync(imagefiles[0]);

		let parsing = new Promise( resolve => {
			Papa.parse(datafiles[0], {
		  		comments: '#',
		  		header: true,
		  		dynamicTyping: true,
				complete: results => {
					if (!results.data[0].x || !results.data[0].y || !results.data[0].dur || !results.data[0].word_id || !results.data[0].word) {
						throw Error('Data malformed. Please use csv style tab-separated format with headers x,y,dur,word_id, word as first line.');
					}
					fixation_data = results.data;
					resolve();
				}
			});
		});
		parsing.then( () => {
			dispatch('load', {image, fixation_data})
		});	
	}
</script>
<div id="overlay">
	<h1>Choose Fixation Data and Image</h1>
	<label>Fixation Data<br/><input bind:files={datafiles} type="file" accept=".txt" /></label>
	<label>Image<br /><input bind:files={imagefiles} type="file" accept=".png, .jpg" /></label>
	<button id="run-button" class="button" on:click={visualize} disabled={!isValid}>Visualize!</button>
</div>

<style>
	#overlay {
		width: 400px;
		height: 200px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
</style>