
import subprocess
from datetime import datetime
import sys
import requests
import telegram
import os
import telegram
# from telegram import ParseMode
import requests
import time
import json
from datetime import datetime

import subprocess
import shlex
import json

from telegram import Bot

from telegram import Bot

def send_video_to_telegram(video_url):
    bot_token = '2135410897:AAH14rU1sjvyP2WqD7lNAgMeYRNinofm4oE'
    chat_id = 'adtlasbot'
    bot = Bot(token=bot_token)
    bot.send_video(chat_id=chat_id, video=video_url)


output_filename = ""

def send_msg_telegram3(msg):
    bot_token = '2135410897:AAH14rU1sjvyP2WqD7lNAgMeYRNinofm4oE'
    channel_name = 'adtlasbot'

    bot = telegram.Bot(token=bot_token)
    bot.send_message(chat_id="@%s" % channel_name,
        text=msg)

def merge_ts_files(input_folder, output_folder):
    # Execute ls command to get the last three .ts files
    ls_command = f"ls -t {input_folder}/*.ts | head -n 5 | tail -n 4"
    file_listing = subprocess.check_output(ls_command, shell=True).decode().splitlines()

    # Reverse the order of the file listing
    file_listing.reverse()
    global output_filename
    # Generate the output file name with the current date and time
    current_datetime = datetime.now().strftime("%Y%m%d%H%M%S")
    output_filename = f"output_{current_datetime}.mp4"
    output_file = f"{output_folder}/output_{current_datetime}.mp4"
    external_file = f"http://173.212.199.208/CBA_videos/output_{current_datetime}.mp4"

    # Create the FFmpeg command to merge the .ts files
    ffmpeg_command = ["ffmpeg", "-i", f"concat:{'|'.join(file_listing)}", "-c", "copy", output_file]


    # Execute the FFmpeg command
    subprocess.run(ffmpeg_command)
    send_video_to_telegram(output_file)
    # response = requests.get(f"http://207.180.254.4:9060/DAIManagement/bca_video/{output_filename}")
    # print("we are here")
    # print(response.text)
    return external_file

# Usage example
input_folder = "/var/www/html/new_level1/2m/2m_hls"
output_folder = "/var/www/html/CBA_videos"
external_file = merge_ts_files(input_folder, output_folder)

# time.sleep(10)

print("external_file:"+external_file)



command = """
curl -X 'POST' \
  'http://102.53.12.137:2023/api/v1/tasks/process' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=' \
  -F 'url="""+external_file+"""' \
  -F 'confidence=' \
  -F 'categories=' \
  -F 'frames=20'
"""

print(command)


process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
output, error = process.communicate()

if output:
    response_data = json.loads(output)

    task_id = response_data.get("task_id")
    message = response_data.get("message")
    url_result = response_data.get("url_result")
    status = response_data.get("status")

    print(f"Task ID: {task_id}")
    print(f"Message: {message}")
    print(f"Result URL: {url_result}")
    print(f"Status: {status}")

if error:
    print(f"Error: {error}")


# Step 2: Check the task status until it's "SUCCESS"
while status != "SUCCESS":
    time.sleep(5)  # wait for 5 seconds before making the next request
    status_url = f"http://102.53.12.137:2023/api/v1/tasks/status/{task_id}"
    status_response = requests.get(status_url, headers={'accept': 'application/json'})
    status_data = status_response.json()
    status = status_data["status"]

# Step 3: If the task status is "SUCCESS", get the result and save it to a JSON file
if status == "SUCCESS":
    result_url = f"http://102.53.12.137:2023/api/v1/tasks/result/{task_id}"
    result_response = requests.get(result_url, headers={'accept': 'application/json'})
    result_data = result_response.json()
    adbread_gen = {}
    # create a timestamped filename
    filename = datetime.now().strftime("%Y-%m-%d_%H%M%S") + f"___{task_id}.json"
    with open("/var/www/html/CBA_json/"+filename, 'w') as outfile:
        json.dump(result_data, outfile)
        # json.dumps(adbread_gen, indent=4, sort_keys=True)
    # send_msg_telegram3("http://173.212.199.208/CBA_json/"+filename)
    response = requests.get(f"http://207.180.254.4:9060/DAIManagement/bca_video/{filename}/{output_filename}")
    print("we are here")
