import shutil
import asyncio
from io import BytesIO

from aiogram.types import InputFile

from bot import bot
import db_utils
from userbot import post_large_track
from var import var
from utils import already_downloading, calling_queue, delete_later


@calling_queue(4)
async def send_track(chat_id, track):
    try:
        stream = await track.download()
        thumb = await track.get_thumb()
        if thumb:
            thumb = BytesIO(thumb)
        filename = f"{track.artist} - {track.title}.mp3".replace('/', '_')
    except ValueError:
        await bot.send_message(
            chat_id,
            "🚫This track is not available "
            f"({track.artist} - {track.title})")
        raise

    await bot.send_chat_action(chat_id, 'upload_audio')
    msg = await bot.send_audio(
        chat_id=-1001246220493,
        audio=InputFile(stream, filename=filename),
        thumb=InputFile(thumb, filename='thumb.jpg'),
        performer=track.artist,
        title=track.title, duration=track.duration)

    file_id = msg.audio.file_id
    await db_utils.add_vk_track(track.full_id, file_id)
    await bot.send_audio(chat_id, file_id)
    var.downloading.pop(track.full_id, None)
    var.vk_tracks.pop(track.full_id, None)


async def send_playlist(chat_id, playlist):
    for track in playlist.tracks:
        print(track.title)
        await send_track(chat_id, track)
