import logging
import os, glob, sys
from importlib import reload
reload(logging)
import coloredlogs
import concurrent.futures
from functions import *
from handling_json_file import *
import json
import cv2
#from moviepy.editor import VideoFileClip
from datetime import datetime, timedelta
import subprocess, json
import time
#
logging.getLogger('sqlalchemy').setLevel(logging.ERROR)
logger = logging.getLogger(__name__)
fh = logging.FileHandler('log_file6.log')
fh.setLevel(logging.INFO)
formatter = coloredlogs.ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
coloredlogs.install(level='INFO')

with open('latest_5_ts.json') as f: #the latest 5 ts in the live
    data = json.load(f)

with open('transition.json') as jsonFile: #used in from of latest_5_ts
    data_tra = json.load(jsonFile)

with open("state.json", "r+") as jsonFile2:  #start or end for the jingle QUE OUT or QUE IN
        data_stat = json.load(jsonFile2)

with open("ref.json", "r+") as jsonFile1:  #one we detect the fist jingle we stop for sometime
        data_ref = json.load(jsonFile1)

with open("detected_jingle.json", "r+") as jsonFile3: #get the ts video of the detected video dynamically
        data_name = json.load(jsonFile3)

with open("all_files.json", "r+") as jsonFile6: #insert all changed ts videos
        all_names = json.load(jsonFile6)

with open("state_ts_video.json", "r+") as jsonFile7: #insert all changed ts videos
        state_video = json.load(jsonFile7)

filename = str(sys.argv[1])

ts_name=filename   #.split('_')[0]

end='no'
#
logger.info('try to post %s',data['ts_4'])
if data_tra['val1']!=ts_name:# and ts_name not in all_names['names']: #when we handle an iframe of the new ts
    logger.info('level111111111111111')
    if data["ts_4"]!="" and '@' not in data["ts_4"] and 'jingle' not in data["ts_4"] and data["ts_4"]!=all_names['names']:  #for the first time. to not post empty video.
        logger.info('posting !!!!!!!!!!!!!!!!!!!')
        logger.info('level2222222222222')
        if check_ts_in_temp(data["ts_4"])==1: #check if the ts video doesn't have the same name as the one in temp folder
            #clip = VideoFileClip("2m/2m_hls/"+data["ts_4"])
            #duration = clip.duration
            try:
                length_ffprobe0 = with_ffprobe("2m/2m_hls/"+data["ts_4"])
            except subprocess.CalledProcessError as e:
                length_ffprobe0 = 0.5
                pass
            #os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
            os.system("echo '#EXTINF:"+str(length_ffprobe0)+",'  >> result.m3u8")
            os.system("echo '2m/2m_hls/"+data["ts_4"]+"'  >> result.m3u8")
            logger.info('post the file %s','2m/2m_hls/'+data["ts_4"])

        if check_ts_in_temp(data["ts_4"])==0:
            logger.info('level333333333333')
            logger.info('ts video is found in temp')
            try:
                length_ffprobe = with_ffprobe("2m/2m_hls/@"+data["ts_4"])
            except subprocess.CalledProcessError as e:
                length_ffprobe = 0.5
                pass
            for key, value in state_video.items():
                logger.info('key = %s',key)
                if key==data["ts_4"]:
                    if state_video[key]=="end":
                        logger.info(' state_video[key] = %s',state_video[key])
                        logger.info('post the file %s','temp/'+data["ts_4"])
                        logger.info('ts video is found in temp')

                        try:
                            if with_ffprobe("2m/2m_hls/@"+data["ts_4"])>1.7:
                                os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
                                # os.system("echo '#EXTINF:"+str(with_ffprobe("2m/2m_hls/@"+data["ts_4"]))+",'  >> result.m3u8")
                                os.system("echo '#EXTINF:"+str(length_ffprobe)+",'  >> result.m3u8")
                                os.system("echo '2m/2m_hls/@"+data["ts_4"]+"'  >> result.m3u8")
                        except subprocess.CalledProcessError as e:
                            pass

                        # if with_ffprobe("2m/2m_hls/@"+data["ts_4"])>1.7:
                        #     os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
                        #     os.system("echo '#EXTINF:"+str(with_ffprobe("2m/2m_hls/@"+data["ts_4"]))+",'  >> result.m3u8")
                        #     os.system("echo '2m/2m_hls/@"+data["ts_4"]+"'  >> result.m3u8")
                        os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
                        os.system("echo '#EXTINF:7.46,'  >> result.m3u8")
                        os.system("cp ts_videos_of_jingles/"+data_name['name']+".ts 2m/2m_hls/"+data_name['name']+".ts")
                        change_name(data_name['name']+".ts",data["ts_4"])
                        logger.info('change the name of ts video and post it')
                        os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
                        os.system("echo '#EXT-X-CUE-OUT' >> result.m3u8")
                        os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")


                    if state_video[key]=="start": #if it's the start of the promotion
                        logger.info(' state_video[key] = %s',state_video[key])

                        os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
                        os.system("echo '#EXT-X-CUE-IN' >> result.m3u8")
                        os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
                        #clip = VideoFileClip("2m/2m_hls/@"+data["ts_4"])
                        #duration = clip.duration
                        # os.system("echo '#EXTINF:"+str(with_ffprobe("2m/2m_hls/@"+data["ts_4"]))+",'  >> result.m3u8")
                        os.system("echo '#EXTINF:"+str(length_ffprobe)+",'  >> result.m3u8")
                        os.system("echo '2m/2m_hls/@"+data["ts_4"]+"'  >> result.m3u8")
                        os.system("echo '#EXT-X-DISCONTINUITY' >> result.m3u8")
            logger.info('end level333333333333')



    #change the values of the two dicts

    logger.info('moving by 1 ts in the cue')

    data["ts_4"]=data["ts_3"]
    data["ts_3"]=data["ts_2"]
    data["ts_2"]=data["ts_1"]
    data["ts_1"]=data["ts_0"]
    #if flag=='0':
    data["ts_0"]=data_tra['val2']
    data_tra['val2']=data_tra['val1']

    data_tra['val1']=filename
    logger.info('adding %s to val1', filename)




    #get_first_ts(data_ref['cte'])
    # first_ts = get_first_ts(data_ref['cte'])
    # logger.info('get_first_ts == %s',first_ts)


    # data_ref['cte']=data_ref['cte']+1 if data_ref['cte']<99 else 99 #once we have posted we should add 1
    # jsonFile1 = open("ref.json", "w+")
    # jsonFile1.write(json.dumps(data_ref))
    # jsonFile1.close()



    f = open("latest_5_ts.json", "w+")
    f.write(json.dumps(data))
    f.close()

    jsonFile = open("transition.json", "w+")
    jsonFile.write(json.dumps(data_tra))
    jsonFile.close()
