import os
import subprocess
from pyrogram import Client, filters
from pyrogram.types import Message

from base import LOGGER, userBot, BOTS, SOFTSUB_DIR, HARDSUB_DIR, DUBBED_DIR, MOVIEO_ENCODES_DIR
from base.utils import Database
from config import THUMB_DIR


@userBot.on_message(filters.private  & filters.text, group=1)
async def commands(_: Client, update: Message):
    text = update.text
    print(text)
    # try:
    command = text.split(',')[0]
    if command == 'upload':
        print('here')
        task_id = int(text.split(',')[1])
        with Database() as db:
            media_task_db = db.get_media_task(task_id, 'id')
        package_id = media_task_db[0][1]
        file_name = media_task_db[0][4]
        with Database() as db:
            package_db = db.get_package(package_id, 'id', 'type')
        task_type = package_db[0][0]
        if task_type == 1:
            file_path = SOFTSUB_DIR
        elif task_type == 2:
            file_path = HARDSUB_DIR
        elif task_type == 3:
            file_path = DUBBED_DIR
        elif task_type == 4:
            file_path = MOVIEO_ENCODES_DIR
        if os.path.exists(f'{file_path}{file_name}'):
            try:
                if task_type in [1,2,3]:
                    command = f"ffprobe -i {file_path}'{file_name}' -v quiet -show_entries format=duration -hide_banner -of default=noprint_wrappers=1:nokey=1 -sexagesimal"
                    res = subprocess.run(command, shell=True, capture_output=True, text=True)
                    if res.returncode == 0:
                        duration = res.stdout.split('.')[0].split(':')
                        sec = 0
                        if int(duration[0]) != 0:
                            sec = int(duration[0]) * 60
                            sec = sec * 60
                        sec += int(duration[1]) * 60
                        sec += int(duration[2])
                        print('here2')
                        await _.send_video(BOTS[0], f'{file_path}{file_name}', caption=f'uploaded,{task_id}', duration=sec, supports_streaming=True, thumb=THUMB_DIR)
                else:
                    await _.send_document(BOTS[0], f'{file_path}{file_name}', caption=f'uploaded,{task_id}')
            except:
                await _.send_message(BOTS[0],f'ERROR,{task_id}')
    # except:
    #     pass
