import { store } from '~/store/store';

export const updateItemInArray = (array, itemIdKey, itemId, updateItemCallback) => {
	const index = array.findIndex((a) => a[itemIdKey] === itemId);
	if (index < 0) return array;
	const item = array[index];
	return [
		...array.slice(0, index),
		updateItemCallback(item),
		...array.slice(index + 1),
	];
};

export const updateMultipleItemInArray = (array, itemIdKey, itemIds, updateItemCallback) => {
	let newArray = array;
	itemIds.forEach((itemId) => {
		newArray = updateItemInArray(newArray, itemIdKey, itemId, updateItemCallback);
	});
	return newArray;
};

export const handleAvatarUriCache = (uri) => {
	if (uri) {
		if (uri.indexOf('ui-avatars') >= 0) {
			return uri;
		}
		return `${uri}?time=${(new Date()).getTime()}`;
	}
	return uri;
};

// onboarding
export const onboardingShow = (feature, element) => {
	const state = store.getState();
	const { username } = state.user;
	return (
		username &&
		(state.onboarding &&
			state.onboarding[feature] &&
			state.onboarding[feature].initialized &&
			state.onboarding[feature].initialized[username] === true) && // check if feature onboarding initialized/ready
		!(state.onboarding &&
			state.onboarding[feature] &&
			state.onboarding[feature][element] &&
			state.onboarding[feature][element][username] === true)
	);
};

export const isOnboardingInitialized = (feature) => {
	// this was created to determine if the user has undergo feature onboarding on the device
	// and if they didnt, this serves as the trigger to the feature onboarding
	const state = store.getState();
	const { username } = state.user;
	return (
		username &&
		(state.onboarding &&
			state.onboarding[feature] &&
			state.onboarding[feature].initialized &&
			state.onboarding[feature].initialized[username] === true)// check if feature onboarding initialized/ready
	);
};
