import { Bookmarks, Bookmark } from "../types/Bookmarks";

function createBookmark(from: browser.bookmarks.BookmarkTreeNode): Bookmark {
	return {
		name: from.title,
		url: from.url
	};
}

export default async (): Promise<Bookmarks> => {
	const treeNode = await browser.bookmarks.getTree();

	const root: Bookmarks = {
		folder: [],
		orphans: []
	};

	const rootNode = treeNode[0].children.find((e)=>e.id === "menu________");

	// Set all top level bookmarks (without folder)
	root.orphans = rootNode.children
		.filter((e)=> e.type === "bookmark" )
		.sort((a,b)=> a.index - b.index )
		.map(createBookmark);

	// Get all top level folders 
	root.folder = rootNode.children
		.filter((e)=> e.type === "folder")
		.filter((e)=> e.children.length > 0)
		.sort((a,b)=> a.index - b.index )
		.map((e)=>{
			const children: Bookmark[] = e.children
				.filter((e)=> e.type === "bookmark")
				.sort((a,b)=> a.index - b.index )
				.map(createBookmark);
			return {
				name: e.title,
				bookmarks: children
			};
		});

	return root;
};
