import type { IMenu, INavigation, IRootState, ISite } from "@ax/types";

const getStateValues = (getState: () => IRootState) => {
	const {
		sites: { currentSiteInfo },
		navigation: {
			editorContent,
			selectedDefault,
			selectedEditorID,
			breadcrumb,
			header,
			footer,
			isNewTranslation,
			currentDefaultsContent,
			selectedContent,
		},
		menu: { savedMenus },
		app: { isSaving, isLoading },
	} = getState();
	const section = editorContent?.[0];
	const { modules } = !!section && section;

	return {
		currentSiteInfo: currentSiteInfo as ISite,
		editorContent,
		selectedDefault,
		selectedEditorID,
		breadcrumb,
		header,
		footer,
		isNewTranslation,
		currentDefaultsContent,
		isSaving,
		isLoading,
		section,
		modules,
		selectedContent,
		menus: savedMenus,
	};
};

const getFormData = (values: any, image?: File | null): FormData => {
	const form = new FormData();
	form.append("navigation", JSON.stringify(values));
	image && form.append("file", image);
	return form;
};

const getTranslatedMenus = (editorContent: INavigation, menus: IMenu[] | null) => {
	const keys = Object.keys(editorContent).filter((k) => editorContent[k]?.component === "MenuContainer");

	if (!keys.length) {
		return editorContent;
	}

	if (!menus || !menus.length) {
		keys.forEach((key) => {
			editorContent[key] = null;
		});
		return editorContent;
	}

	keys.forEach((key) => {
		const menuName = (editorContent[key] as IMenu).name;
		const translatedMenu = menus.find((menu) => menu.name === menuName);
		const hasElements = !!translatedMenu?.elements?.length;

		if (translatedMenu && hasElements) {
			editorContent[key] = translatedMenu;
		} else {
			editorContent[key] = null;
		}
	});

	return editorContent;
};

export { getStateValues, getFormData, getTranslatedMenus };
