import { writable, get, derived } from 'svelte/store';
import { 
	channel_number, 
	dataset_min,
	dataset_max,
	dataset_rows
} from './lib/canvas_properties';
import { displayXaxis } from './lib/xAxis';

export let socket = new WebSocket('ws://localhost:8001');

const default_dir = "/Users/jsencak/Documents/bubu";
export const directory_store = writable("");
directory_store.set(default_dir);

export function openedFile() {
	get(files_store).forEach(el => {
		if (el.opened) {
			return el.long_name;
		}
	})
	return null;
}

export const stream_state = writable(false);    // is heatmap redrawing?
export const messageStore = writable('');		// messages ??? used ???
export const files_to_choose = writable([]);	// fullpath filenames
export const files_to_display = writable([]);	// displayed list of files
export const filename_store = writable('');		// filename
export const dataset_list = writable([]);  		// displayed select of datasets contained in a .h5 file
export const datasetname_store = writable('');  // name of the dataset
export const loading = writable(false);         // display loader when true
export const data_store = writable([]);  		// displayed data
export const opened_file_store = writable("File closed.");  // filename to display for opened file
export const opened_file_obj = writable({long_name: ""});
export const files_store = writable([]);		// all files to choose from
export const data_window = writable([]);		// ???
export const play_btn_state = writable(false);
export const selected_channels = writable("all");

export const inner_stream_state = writable(false);

// Connection opened
socket.addEventListener('open', function (event) {
	console.log("Websocket is open.");
	find_files_f();
});

const waitForOpenSocket = (sckt) => {
	return new Promise((resolve) => {
	  if (sckt.readyState !== sckt.OPEN) {}
	});
}

let recvd;
let files_set = [];

socket.addEventListener('message', function (event) {
	// Listen for messages
	recvd = JSON.parse(event.data);
	console.log("MESSAGE: ", recvd);
	if (recvd.type == "choose_files") {
		recvd.files.forEach(element => {
			files_set.push(element.split("/").pop())
		});
		files_to_display.set([...files_set]);
		files_to_choose.set(recvd.files);
		
		let tmp = [];
		recvd.files.forEach(element => {
			tmp.push({
				long_name: element,
				short_name: element.split("/").pop(),
				selected : false,
				opened : false,
				dataset_list : []
			});
		});
		files_store.set(tmp);
	}
	if (recvd.type == "dataset_content") {
		dataset_list.set(recvd.content);
		let tmp = [];
		get(files_store).forEach(element => {
			if (element.long_name === recvd.filename){
				tmp.push({
					long_name: element.long_name,
					short_name: element.short_name.split("/").pop(),
					selected : true,
					opened : true,
					dataset_list : recvd.content
				});
			} else {
				tmp.push({
					long_name: element.long_name,
					short_name: element.short_name.split("/").pop(),
					selected : false,
					opened : false,
					dataset_list : element.dataset_list
				});
			}
		})
		files_store.set(tmp);
	}

	if (recvd.type == "data") {
		// Equivalent
		data_store.update(items => [recvd.data, ...items]);
	}
	if (recvd.type == "properties") {
		channel_number.set(recvd.number_of_channels);
		console.log(get(channel_number))
		dataset_min.set(recvd.min)
		dataset_max.set(recvd.max)
		dataset_rows.set(recvd.number_of_rows)
		displayXaxis()
	}
	if (recvd.type == "ready") {
		loading.set(false);
		play_btn_state.set(true);
	}
});

/* Send messages via websocket */
export const sendMessage = async (message) => {
	console.log("SENDING", message);
	if (socket.readyState !== socket.OPEN){
		try {
			await waitForOpenSocket(socket);
			socket.send(JSON.stringify(message));
		} catch (err) {console.error(err)}
	} else {
		socket.send(JSON.stringify(message));	
	}
}

export function pause_data_flow() {
	sendMessage({
		type: "stream",
		value: false
	});
}

export function find_files_f(){
	sendMessage({
		type: "path",
		path: get(directory_store),
		suffix: ".h5"
	});
}
