import os
import shutil
import re
from celery import Celery
from pyrogram import Client
from pyrogram.types.bots_and_keyboards import callback_query
from pyrogram.types import (InlineKeyboardButton)
from base import Bot, DOWNLOAD_DIR, SUBTITLE_DIR, DEFAULT_QUALITIES
from base.utils.database import Database
from base.utils.buttons import auto_inline_panel, cancel_task_2
from config import SOFTSUB_DIR, HARDSUB_DIR, DUBBED_DIR, MOVIEO_ENCODES_DIR, DEFAULT_QUALITIES


@Bot.on_callback_query(group=1)
async def tasks_and_subtitles(_: Client, update: callback_query.CallbackQuery):
    user_id = update.from_user.id
    username = update.from_user.username
    callback_data = update.data
    message_id = update.message.id
    # try:
    command = callback_data.split(',')[0]
    param = callback_data.split(',')[1]
    if command == 'receive_sub':
        with Database() as db:
            subtitles_db = db.get_subtitle(int(param),'file_name')
        file_name = subtitles_db[0][0]
        await _.send_document(user_id,f'{SUBTITLE_DIR}mvo_{file_name}')
    elif command == 'change_subtitle':
        with Database() as db:
            db.update_user(user_id,'state',2)
            db.update_media_task(int(param),'sub_or_audio',None)
            media_task_db = db.get_media_task(int(param),'id','package_id,file_name')
            package_id = media_task_db[0][0]
            file_name = media_task_db[0][1]
            db.update_user(user_id,'package_id',package_id)
        await _.delete_messages(user_id,message_id)
        await _.send_message(user_id,f'لطفا زیرنویس جدید برای فایل {file_name} را ارسال کنید:')
    elif command == 'change_dubbed_audio':
        with Database() as db:
            db.update_user(user_id,'state',2)
            db.update_media_task(int(param),'sub_or_audio',None)
            media_task_db = db.get_media_task(int(param),'id','package_id,file_name')
            package_id = media_task_db[0][0]
            file_name = media_task_db[0][1]
            db.update_user(user_id,'package_id',package_id)
        await _.delete_messages(user_id,message_id)
        await _.send_message(user_id,f'لطفا زیرنویس جدید برای فایل {file_name} را ارسال کنید:')
    elif command == 'change_file_name':
        with Database() as db:
            db.update_user(user_id,'state',3)
            media_task_db = db.get_media_task(int(param), 'id', 'package_id,file_name')
            db.update_media_task(int(param),'file_name',None)
            package_id = media_task_db[0][0]
            file_name = media_task_db[0][1]
            db.update_user(user_id,'package_id',package_id)
        await _.delete_messages(user_id,message_id)
        await _.send_message(user_id,f'لطفا نام جدید برای فایل {file_name} را ارسال کنید:')
    elif command in DEFAULT_QUALITIES:
        buttons = []
        buttons.append([InlineKeyboardButton('تغییر نام فایل', f'change_file_name,{int(param)}')])
        for quality in DEFAULT_QUALITIES:
            if quality == command:
                buttons.append([InlineKeyboardButton(f'✅ {quality}', f'{quality},{int(param)}')])
            else:
                buttons.append([InlineKeyboardButton(f'{quality}', f'{quality},{int(param)}')])
        buttons.append([InlineKeyboardButton('آغاز عملیات', f'start_task,{int(param)},{command}')])
        await update.edit_message_text(update.message.text, reply_markup=auto_inline_panel(buttons))
    elif command == 'start_task':
        # try:
        with Database() as db:
            media_task_db = db.get_media_task(int(param),'id','package_id,file,file_name,sub_or_audio')
        package_id = media_task_db[0][0]
        file_id = media_task_db[0][1]
        file_name = media_task_db[0][2]
        sub_or_audio = media_task_db[0][3]
        with Database() as db:
            package_db = db.get_package(package_id,'id','type')
        task_type = package_db[0][0]
        await update.edit_message_text('⏳ در حال انجام عملیات...')
        celery_app = Celery(
            "requests",
            broker="redis://localhost:6379/0",
        )
        if task_type in [1,5]:
            request_type = 'isolate_softsub_converter'
            quality = None
            shutil.move(f'{SUBTITLE_DIR}{sub_or_audio}',f'/var/www/html/auto_sub_bot/subtitles/{file_id}{sub_or_audio[-3:]}')
            sub_or_audio = f'{file_id}{sub_or_audio[-3:]}'
        elif task_type in [2,6]:
            request_type = 'isolate_hardsub_converter'
            quality = None
            shutil.move(f'{SUBTITLE_DIR}{sub_or_audio}',f'/var/www/html/auto_sub_bot/subtitles/{file_id}{sub_or_audio[-3:]}')
            sub_or_audio = f'{file_id}{sub_or_audio[-3:]}'
        elif task_type == 3:
            request_type = 'isolate_dubbed_converter'
            quality = None
        else:
            for quality in DEFAULT_QUALITIES:
                if re.search(r'\b' + quality + r'\b', file_name):
                    quality = quality
                    break
                else:
                    quality = None
            request_type = 'isolate_quality_converter'
        celery_app.send_task(
            "celery_tasks.tasks.task_router.route_task",
            args=[request_type, 0],
            kwargs={
                "admin_user_id": user_id,
                "username": f'@{username}',
                "file_id": file_id,
                "file_name": file_name,
                "sub_or_audio": sub_or_audio,
                'quality': quality
            },
            queue='router'
        )
        # except:
        #     pass
    elif command == 'cancel':
        task_id = int(param)
        with Database() as db:
            media_task_db = db.get_media_task(task_id,'id','file_name,sub_or_audio,status,package_id')
        file_name = media_task_db[0][0]
        sub_or_audio = media_task_db[0][1]
        status = media_task_db[0][2]
        package_id = media_task_db[0][3]
        with Database() as db:
            package_db = db.get_package(package_id,'id','type')
        task_type = package_db[0][0]
        with Database() as db:
            db.delete_media_task(task_id, 'id')
        await update.edit_message_text('❗️ تسک موردنظر لغو شد.')
        if status == 1:
            if task_type in [1,5]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '')}")
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '')}")
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
            elif task_type in [2,6]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '').replace('ass','srt')}")
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '').replace('ass','srt')}")
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
        elif status == 3:
            os.remove(f'{DOWNLOAD_DIR}{file_name}')
            if task_type in [1,5]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '')}")
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '')}")
            elif task_type in [2,6]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '').replace('ass','srt')}")
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '').replace('ass','srt')}")
        elif status == 4:
            os.remove(f'{DOWNLOAD_DIR}{file_name}')
            if task_type in [1,5]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '')}")
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '')}")
                os.remove(f'{SOFTSUB_DIR}{file_name}')
            elif task_type in [2,6]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '').replace('ass','srt')}")
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '').replace('ass','srt')}")
                os.remove(f'{HARDSUB_DIR}{file_name}')
            elif task_type == 3:
                audio_name = sub_or_audio.split('/')[-1]
                os.remove(f'{DUBBED_DIR}{audio_name}')
                try:
                    os.remove(f'{DUBBED_DIR}{file_name}')
                except:
                    pass
            elif task_type == 4:
                try:
                    os.remove(f'{MOVIEO_ENCODES_DIR}{file_name}')
                except:
                    pass
        elif status in [5,6]:
            os.remove(f'{DOWNLOAD_DIR}{file_name}')
            if task_type in [1,5]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '')}")
                os.remove(f'{SOFTSUB_DIR}{file_name}')
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '')}")
            elif task_type in [2,6]:
                os.remove(f"{DOWNLOAD_DIR}{sub_or_audio.replace('mvo_', '')}")
                os.remove(f'{HARDSUB_DIR}{file_name}')
                os.remove(f'{SUBTITLE_DIR}{sub_or_audio}')
                os.remove(f"{SUBTITLE_DIR}deleted_{sub_or_audio.replace('mvo_', '')}")
            elif task_type == 3:
                os.remove(f'{DUBBED_DIR}{file_name}')
                os.remove(f"{DUBBED_DIR}{sub_or_audio.split('/')[-1]}")
            elif task_type == 4:
                os.remove(f'{MOVIEO_ENCODES_DIR}{file_name}')

    # except:
    #     pass