import { getUserRecord } from "db/dbUser";
import items from "items";
import { Command, sendMessage } from "lib/commandUtils";
import parseCommandArgs from "lib/parseCommandArgs";
import User from "user";

export default new Command({
	name: "inventory",
	aliases: ["inv", "inventory", "pocket"],
	usertype: "chatter",
	execution: async (msg, user) => {
		const args = parseCommandArgs(msg.messageText);
		let target: User = user;
		if (args[0]) {
			const obj = await User.initUsername(args[0].toLowerCase());
			if (!obj) {
				await sendMessage(`User ${args[0]} doesn't exist`, msg.messageId);
				return;
			}
			target = obj;
		}

		const data = await getUserRecord(target);
		const messagedata: string[] = [];
		for (const [key, amount] of Object.entries(data.inventory)) {
			if (amount === 0) continue;
			const itemselection = items.get(key);
			messagedata.push(
				`${itemselection?.prettyName}${amount === 1 ? "" : itemselection?.plural}: ${amount}`,
			);
		}

		if (messagedata.length === 0) {
			await sendMessage(`${target.displayName} has no items`, msg.messageId);
			return;
		}
		await sendMessage(
			`Inventory of ${target.displayName}: ${messagedata.join(", ")}`,
			msg.messageId,
		);
	},
});
