import { writable, get } from 'svelte/store';
import { browser } from '$app/environment';

export const currentStream = writable({});
export const currentSongIndex = writable(null);

export const favoritedStreams = writable(
	new Set(JSON.parse((browser && localStorage.getItem('favoritedStreams')) || '[]'))
);

if (browser) {
	favoritedStreams.subscribe((val) => {
		localStorage.setItem('favoritedStreams', JSON.stringify(Array.from(val)));
	});
}

export const tagList = [
	'acoustic',
	'electronic',
	'orchestral',
	'rock',
	'pop',
	'metal',
	'aggressive',
	'folk',
	'jazzy',
	'dance.music',
	'untz',
	'breakbeats',
	'electronica',
	'chiptune',
	'left.field',
	'denpa',
	'vocaloid',
	'funky',
	'lush',
	'noisy',
	'psychedelic',
	'dark',
	'calm',
	'moody',
	'uplifting'
];

let timestampList;

// utility

function locationOf(element, array, start, end) {
	start = start || 0;
	end = end || array.length;
	var pivot = parseInt(start + (end - start) / 2, 10);
	if (end - start <= 1 || array[pivot] === element) return pivot;
	if (array[pivot] < element) {
		return locationOf(element, array, pivot, end);
	} else {
		return locationOf(element, array, start, pivot);
	}
}

// exported methods

export function getSongAtTime(currentTime) {
	return locationOf(currentTime, timestampList) - 1;
}

// less operations needed when doing regular lookups
export function updateCurrentSong(currentTime, songIndex) {
	function updateCurrentSongRecurse(songIndex) {
		if (currentTime >= timestampList[songIndex + 2]) {
			return updateCurrentSongRecurse(songIndex + 1);
		} else if (currentTime < timestampList[songIndex + 1]) {
			return updateCurrentSongRecurse(songIndex - 1);
		}
		return songIndex;
	}

	currentSongIndex.set(updateCurrentSongRecurse(songIndex));
}

export function updateCurrentStream(stream) {
	currentStream.set(stream);
	timestampList = [-Infinity, ...stream.tracks.map((track) => track[0]), Infinity];
	currentSongIndex.set(0);
}
