import { Interaction } from 'discord.js';
import { entersState, getVoiceConnection, joinVoiceChannel } from '@discordjs/voice';
import { entersState,	joinVoiceChannel,	VoiceConnectionStatus } from '@discordjs/voice';
import { configs } from "./configs.ts";
import { client, subscriptions } from "./index";
import { MusicSubscription } from './subscription.ts';

export function channelIsAllowed(guild: string, channel: string) {
	if(`${guild}:${channel}` in configs.allowed_text_channels) {
		return true;
	}

	return false;
}

export async function ensureVoiceConnection(interaction: Interaction) {
	const subscription = subscriptions.get(interaction.guildId);
	if(subscription) return;
	try {
		const channel = interaction.member.voice.channel;
		const subscription = new MusicSubscription(
			joinVoiceChannel({
				channelId: channel.id,
				guildId: channel.guild.id,
				adapterCreator: channel.guild.voiceAdapterCreator,
			}),
			channel.guild.id,
		);
		subscription.voiceConnection.on('error', console.warn);
		subscriptions.set(interaction.guildId, subscription);
		await entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
	} catch(err) {
		console.error(err);
		await interaction.followUp({content: `Couldn't join voice channel`});
	}
}

export function formatCallbackData(text: string, title?: string) {
	if(title) {
		return {
			content: "",
			embeds: [{
				color: configs.embed_color,
				description: text,
				title: title
			}]
		}		
	}
	return {
		content: "",
		embeds: [{
			color: configs.embed_color,
			description: text
		}]
	}
}

export async function getAllowedTextChannel(subscription: MusicSubscription) {
	const guild = await client.guilds.fetch(subscription.voiceConnection.joinConfig.guildId);
	const channels = await guild.channels.fetch();

	for(const [id, channel] of channels) {
		if(channel.type == 0 && configs.allowed_text_channels.includes(`${guild.name.toLowerCase()}:${channel!.name!.toLowerCase()}`)) {// text channel
			return client.channels.cache.get(id);
		}
	}

	return guild.channels.filter(c => c.type === 'text').find(x => x.position == 0);
}

export const waitingForResponse = {
	type: 2,
	content: "waiting for response..."
};

function errorMessage(message: string) {
	return <CreateMessage>{
		embeds: [<Embed>{
			color: configs.embed_color,
			description: message
		}]
	}
}

export async function errorMessageCallback(guildId: bigint, message: string) {
	const channel = await getAllowedTextChannel(guildId);
	await sendMessage(channel.id, errorMessage(message));
}

export function isPlaylist(query: string) {
  if(query.includes("playlist")){
    return true;
  }

  return false;
}
