import moment from "moment";

export function dateSorter(a: any, b: any, direction: "asc" | "desc", key: string) {
	if (!a[key] && !b[key]) return 0;
	if (a[key] && !b[key]) return direction === "asc" ? 1 : -1;
	if (!a[key] && b[key]) return direction === "asc" ? -1 : 1;
	if (moment(a[key]).isAfter(b[key])) return direction === "asc" ? 1 : -1;
	if (moment(b[key]).isAfter(a[key])) return direction === "asc" ? -1 : 1;
	return 0;
}

export async function asyncSorter<T>(array: T[], sorterFunction: (a: T, b: T) => Promise<number>): Promise<T[]> {
	let swapped = false;
	do {
		swapped = false;
		for (let i = 0; i < array.length - 1; i++) {
			const result = await sorterFunction(array[i], array[i + 1]);
			if (result < 0) {
				const aux = array[i + 1];
				array[i + 1] = array[i];
				array[i] = aux;
				swapped = true;
			}
		}
	} while (swapped);

	return array;
}

export function env(key: string) {
	return (window as any).__ENV[key];
}

export const convertBase64 = (file: File) => {
	return new Promise((resolve, reject) => {
		const fileReader = new FileReader();
		fileReader.readAsDataURL(file);
		fileReader.onload = () => {
			resolve(fileReader.result);
		};
		fileReader.onerror = (error) => {
			reject(error);
		};
	});
};

export const mapBy = <T>(obj: T[], key: keyof T) => {
	if (!obj) return undefined;
	return obj.map((i) => i[key]);
};
export const filterBy = <T>(obj: T[], key: keyof T, value: any) => obj.filter((i) => i[key] === value);

export const serialize = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));
