import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from celery_tasks.celery import app
from config import SOFTSUB_DIR,STREAMS_DIR
from base.utils.funcs import run_command
from base.utils.subtitle_editor import *

@app.task(queue='softsubs')
def convert_to_softsub(first_step_res: dict, file_name: str):
    status = first_step_res.get('status')
    if status:
        print(f'\n**********************\n--- trying to convert the file to soft sub... \n**********************')
        server_file_name = first_step_res.get('server_file_name')
        subtitle = first_step_res.get('subtitle')
        sync_score = first_step_res.get('sync_score')

        command = f"ffmpeg -i {DOWNLOAD_DIR}{server_file_name} -n -sub_charenc 'UTF-8' -f srt -i {SUBTITLE_DIR}{subtitle} -map 0:0 -map 0:1 -map 1:0 -disposition:s:0 default -c:v copy -c:a copy -c:s srt {SOFTSUB_DIR}{server_file_name}"
        run_command(command, 'something went wrong when trying to convert file to soft sub.')

        command = f"ffmpeg  -y -i {SOFTSUB_DIR}{server_file_name} -map 0:s:m:language:per {STREAMS_DIR}{subtitle}"
        run_command(command, 'something went wrong when trying to get persian soft subtitle.')

        if not os.path.exists(f'{STREAMS_DIR}{subtitle}'):
            command = f"ffmpeg  -y -i {SOFTSUB_DIR}{server_file_name} -map 0:s:0 {STREAMS_DIR}{subtitle}"
            run_command(command, 'something went wrong when trying to get unknown language soft subtitle.')

        command = f"ffmpeg  -y -i {STREAMS_DIR}{subtitle} {STREAMS_DIR}{subtitle[:-3]}vtt"
        run_command(command, 'something went wrong when trying to convert to vtt subtitle format.')

        command = f"ffmpeg  -y -i {SOFTSUB_DIR}{server_file_name} -codec copy {STREAMS_DIR}{server_file_name[:-3]}mov"
        run_command(command, 'something went wrong when trying to convert to mov video format.')

        caption = f'{file_name}\n\nhttp://157.180.58.225/player.php?file_name={server_file_name[:-3]}mov&subtitle={subtitle[:-3]}vtt\n\nsync score: {sync_score}'
        first_step_res['caption'] = caption
        return first_step_res
    else:
        return {'status': False}