'''
iframe.py - ffmpeg i-frame extraction
'''

import sys, getopt, os
import subprocess
from pathlib import Path
import glob
import time
import os.path
# from moviepy.editor import VideoFileClip

import json
def read_json_file(path_file:str="data.json"):
    # Opening JSON file
    f = open(path_file)
    # returns JSON object as a dictionary
    data = json.load(f)
    # Closing file
    f.close()
    return data
def search(data, search:str, default:str):
    """ search for specific keys """
    search_ret = []
    if isinstance(data, (list, tuple)):
        for d in data:
            for key in d.keys():
                if key == search:
                    try:
                        search_ret.append(d[key])
                    except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                        pass
    else:
        for key in data.keys():
            if key == search:
                try:
                    search_ret.append(data[key])
                except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                    pass
    if search_ret:
        val = search_ret
    else:
        val = default
    return val
# Function : update the json file with the new data and save it
# Attributes:
#   - data: the json data
#   - update_key: the key to update
#   - value: the new value
#   - saved_path: the path to the json file
# Returns:
#   - data: the updated json data
def update(data, update_key:str, value:str, saved_path:str="data.json"):
    """ update a specific key """
    # update the value of the key in the json data
    if isinstance(data, (list, tuple)):
        for d in data:
            for key in d.keys():
                if key == update_key:
                    try:
                        d[key] = value
                    except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                        pass
    else:
        for key in data.keys():
            if key == update_key:
                try:
                    data[key] = value
                except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                    pass

    # If the saved_path exists, we update it with the new data
    if saved_path:
        # Writing JSON data to file
        with open(saved_path, 'w') as f:
            json.dump(data, f)
    return data






segment = str(sys.argv[1])

if os.path.isfile("2m_hls/"+segment) and ".ts" in segment:

    print("segment => "+segment)
    # clip = VideoFileClip("2m_hls/"+segment)
    # duration = int(clip.duration)
    duration = 6
    ts = time.time()
    ts = "."+str(ts).split('.')[0]
    now = str(segment).split('.')[0]

    home = os.path.expanduser("~")
    ffmpeg = 'ffmpeg'
    cwd = os.getcwd()

    # video = 25 frame par second

    cmd = "ffmpeg -y -i 2m_hls/"+segment+" -vf 'select=gt(scene\,0.10)' -vsync vfr -frame_pts true iframes_live_old/"+now+"_%d_"+str(duration)+".png"
    # cmd = "ffmpeg -y -i 2m_hls/"+segment+" -vf 'select=gt(scene\,0.10)' -vsync vfr -frame_pts true iframes_live/"+now+str(ts)+"_%d_"+str(duration)+".png"
    # cmd = "ffmpeg -y -i 2m_hls/"+segment+" -vf \"select='eq(pict_type,PICT_TYPE_I)'\" -vsync vfr -frame_pts true iframes_live/"+now+str(ts)+"_%d_"+str(duration)+".png"
    print(cmd)
    # python3 iframe_scanner.py $file
    os.system(cmd)
    # os.system("rm 2m_hls/"+segment)
    # print("python3 iframe_scanner2.py "+now+"_dfsd")
    # os.system("python3 iframe_scanner2.py "+now+"_sdfsd > /dev/null 2>&1 & ")

    # here I will do copy the m3u8 file from original to final_2m_hls
    # os.system("cp 2m_hls/"+segment+" DAI_2m_hls/"+segment)
    #
    # path_file="data.json"
    # data = read_json_file(path_file=path_file)
    # #getting the data with key
    # inside_adbreak = search(data, search="inside_adbreak", default="Attribute Not Found !")
    # level = search(data, search="level", default="Attribute Not Found !")
    # insert_new_adbreak = search(data, search="insert_new_adbreak", default="Attribute Not Found !")
    # booked_adbreak_duration = search(data, search="adbreak_duration", default="Attribute Not Found !")
    # current_debt = search(data, search="dept_in_seconds", default="Attribute Not Found !")
    #
    #
    # if inside_adbreak[0] == "no" or level[0] == 1:
    #     print("im inside")
    #     with open(r"DAI_2m_hls/index.m3u8", 'r') as fp:
    #         num_lines = sum(1 for line in fp)
    #         print('Total lines:', num_lines)
    #         if num_lines>190:
    #
    #             os.system("sed -i.bak '5d' DAI_2m_hls/index.m3u8")
    #             os.system("sed -i.bak '5d' DAI_2m_hls/index.m3u8")
    #     os.system("echo '#EXTINF:3.000000,'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '../2m_hls/"+segment+"'  >> DAI_2m_hls/index.m3u8")
    # # else:
    # #     print("im outside")
    # #     os.system("echo '#EXTINF:1.000000,'  >> DAI_2m_hls/index.m3u8")
    # #     os.system("echo '../samples/test_1.ts'  >> DAI_2m_hls/index.m3u8")
    #
    # if level[0] == 3 and insert_new_adbreak[0] == "on":
    #     print("im inside level 3")
    #
    #     insert_new_adbreak = update(data, update_key="insert_new_adbreak", value="off", saved_path=path_file)
    #     num_of_segments = round(booked_adbreak_duration[0]/10)
    #     os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '#EXTINF:3.160000,'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '../jingles/jingle_1_0.ts'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '#EXTINF:3.840000,'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '../jingles/jingle_1_1.ts'  >> DAI_2m_hls/index.m3u8")
    #
    #     os.system("echo '#EXT-X-CUE-OUT' >> DAI_2m_hls/index.m3u8")
    #
    #
    #     for x in range(num_of_segments):
    #         os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
    #         os.system("echo '#EXTINF:10.000000,'  >> DAI_2m_hls/index.m3u8")
    #         os.system("echo '../samples/test_10.ts'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '#EXT-X-CUE-IN' >> DAI_2m_hls/index.m3u8")
    #
    #     os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '#EXTINF:3.160000,'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '../jingles/jingle_1_0.ts'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '#EXTINF:3.840000,'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '../jingles/jingle_1_1.ts'  >> DAI_2m_hls/index.m3u8")
    #     os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
    #     new_debt = current_debt[0] + booked_adbreak_duration[0]
    #     new_debt = update(data, update_key="dept_in_seconds", value=new_debt, saved_path=path_file)
