import { H3Event, EventHandlerRequest } from "h3";
import { GridFSBucket } from "mongodb";
import mongoose, { Document } from "mongoose";
import { norm, stringifyStream } from "@functions";
import { IStory } from "@models/stories";
import { IChapter } from "@models/stories/chapter";
import getBucket from "../storyHelpers/getBucket";
import { SingleChapterResult } from "@client/types/slightlyDifferentStory";

export default async function (
	story: Document<number, {}, IStory> & IStory,
	event: H3Event<EventHandlerRequest>,
	cindex: number,
): Promise<SingleChapterResult> {
	const finObj: any = story.toObject();
	const cloned: any & { chapters: IChapter[] } = { ...finObj };
	delete finObj.chapters;
	const bucket = getBucket();
	let ds = bucket.openDownloadStreamByName(
		`/stories/${
			cloned.chapters[cindex || event.context.chapterIndex || 0].id
		}.txt`,
	);
	let stream = await stringifyStream(ds);
	finObj.currentChapter = {
		...cloned.chapters[cindex || event.context.chapterIndex || 0],
		text: norm(stream),
	};
	finObj.totalChapters = story.chapters.length;
	finObj.chapterNames = story.chapters.map((a) => a.title);
	return finObj;
}
