import { Interaction } from 'discord.js';

import { subscriptions } from "../index.js";
import { ensureVoiceConnection, formatCallbackData, waitingForResponse } from "../utils.ts";

function notLoopingResponse(interaction: Interaction) {
	const subscription = subscriptions.get(interaction.guildId);
	return formatCallbackData(`Looping is already disabled. 
		Currently playing: **${subscription.queue[0].title}**, added by ${subscriptions.queue[0].added_by}`);
}

const nothingToLoopResponse = formatCallbackData(`The queue is empty.`);

function loopDisabledResponse(interaction: Interaction) {
	const subscription = subscriptions.get(interaction.guildId);
	return formatCallbackData(`Looping the current song has been disabled. 
			Currently playing: **${subscription.queue[0].title}**, added by ${subscription.queue[0].addedBy}`);
}

export const unloopCommand = {
	name: "unloop",
	description: "Disables looping the current song. At the current song's end, the queue will proceed as normal."
};

export async function unloop(interaction: Interaction) {
	if (!interaction.guildId) return;
	await ensureVoiceConnection(interaction);
	const subscription = subscriptions.get(interaction.guildId);
	await interaction.reply(waitingForResponse);

	if(!subscription.playing) {
		await interaction.editReply(interaction.token, nothingToLoopResponse);
	} else if(subscription.looping){
		subscription.audioPlayer.loop = false;
		await interaction.editReply(loopDisabledResponse(interaction));
	} else {
		await interaction.editReply(notLoopingResponse(interaction));
	}
}