#import packages
import pandas as pd
import mysql.connector
import time
import os
import cv2
import sys
import logging
from importlib import reload
reload(logging)
import coloredlogs
import sqlalchemy
from datetime import timedelta
from datetime import datetime
from pathlib import Path
from handling_json_files import *
from functions import *
import json
import concurrent.futures
import shutil
import glob
import json
from dotenv import load_dotenv
load_dotenv()

# Get environment variables
user = os.getenv('db_user')
password = os.getenv('db_password')
localhost = os.getenv('db_localhost')
db_name = os.getenv('db_name')
table_name=os.getenv('channel_name')
channel_name=table_name

logging.getLogger('sqlalchemy').setLevel(logging.ERROR)
logger = logging.getLogger(__name__)
# Create a filehandler object
fh = logging.FileHandler(table_name+'/'+table_name+'.log')
fh.setLevel(logging.INFO)
# Create a ColoredFormatter to use as formatter for the FileHandler
formatter = coloredlogs.ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
coloredlogs.install(level='INFO')
#
with open("similarity.json", "r+") as jsonFile:
    data = json.load(jsonFile)

with open("detective.json", "r+") as jsonFile1:
    data_detective = json.load(jsonFile1)


with open("info.json", "r+") as jsonFile2:
    new_data = json.load(jsonFile2)

with open("break.json", "r+") as jsonFile3:
    break_data = json.load(jsonFile3)

filename = str(sys.argv[1])

current_date_time2=datetime.strptime(time.strftime("%H:%M:%S"),"%H:%M:%S")
jingles=[file for folder in get_folders_to_handle(table_name,user,password,localhost,db_name) for file in glob.glob(table_name+"/iframes/"+folder+"/*.png")]

#def main(jingle):
for jingle in jingles:
    
    with open("break.json", "r+") as jsonFile3:
        break_data = json.load(jsonFile3)
    
    current_date_time2=datetime.strptime(time.strftime("%H:%M:%S"),"%H:%M:%S")

    if str(current_date_time2)<break_data['date']:
        logger.info('we still handling %s',data_detective['current_name'])

    else:

        i_frame_time= time.strftime("%H:%M:00")
        #jingles=[file for folder in get_folders_to_handle(table_name,user,password,localhost,db_name) for file in glob.glob("/home/fefo/Desktop/official_project/"+table_name+"/iframes/"+folder+"/*.png")]

    
        my_token = '5522894419:AAE9CeONlV2lfmUGqbXGZAHC-l1Z90TMuD4'
        current_date_time=datetime.strptime(time.strftime("%H:%M:%S"),"%H:%M:%S")
        time_of_chow=''
    
        #check the similarity between the two images
        logger.info('Measure the similarity between %s and %s',filename,jingle)
        print('=================')
        print('the filename is ', filename)
        print('the jingle is ', jingle)
        result= compare_image(filename,jingle)
        logger.info('The result of the similarity between %s and %s is %s',filename,jingle,result)


        if result<100:
            logger.info('The %s and %s are NOT similar',filename,jingle)

        else:
        
            logger.info("there is similarity between ,%s and %s are SIMILAR with result %s",filename,jingle,result)
            #send("there is similarity between "+jingle+" and "+filename +" with results = "+str(result),"-1001778433367", token=my_token)
            telegram_bot_sendtext("there is similarity between "+jingle+" and "+filename +" with results = "+str(result))
            if data['cte']==0:

                add_one()
                add_time()
        
            if data['cte']==1: #or data['cte']==2:
                add_one()
            if data['cte']==2:
                if str(current_date_time)<data['date']:
                    break_date()
                    #send("This is the intro of "+jingle.split('/')[-2],"-1001778433367", token=my_token)
                    #telegram_bot_sendtext('This is the intro of '+jingle.split('/')[-2])
                    #logger.info('The %s and %s are similar',filename,jingle)
                    #send("start updating !!!","-1001778433367", token=my_token)
                    logger.info("it's the intro of %s ",jingle.split('/')[-2])
                    telegram_bot_sendtext("it's the intro of "+jingle.split('/')[-2]+" !!")

                    time_of_chow=get_date_of_jingle(channel_name,jingle.split('/')[-2],user,password,localhost,db_name)[0]
                    dif_time = datetime.strptime(i_frame_time,"%H:%M:%S") - datetime.strptime(':'.join(time_of_chow.split(':')[:-1]),"%H:%M:%S")
                    with open("detective.json", "r+") as jsonFile1:
                        data_detective = json.load(jsonFile1)

                        if data_detective['next_name']==jingle.split('/')[-2]:

                            data_detective["current_name"]=data_detective["next_name"]
                            data_detective["next_name"]=get_next_show(channel_name,user,localhost,password,db_name,jingle.split('/')[-2])

                            jsonFile1 = open("detective.json", "w+")
                            jsonFile1.write(json.dumps(data_detective))
                            jsonFile1.close()

                                #send("This jingle has not been replaced by "+jingle.split('/')[-2]+" !!","-1001778433367", token=my_token)


                        else:
                            #send("This jingle has been replaced by "+jingle.split('/')[-2]+" !!","-1001778433367", token=my_token)
                            telegram_bot_sendtext("This jingle has been replaced by "+jingle.split('/')[-2]+" !!")

                    if dif_time==0:
                        logger.info('The %s and the %s have the same time',filename,jingle)
                        back_cte()
                        back_time()

                    else:
                        #calculate_total_delay(dif_time)
                        logger.info('The %s and the %s DONT NOT have the same time',filename,jingle)
                        update_jingle_time(table_name,jingle.split('/')[-2],user,password,localhost,db_name)
                        logger.info('The update is done for this %s',jingle.split('/')[-2])
                        back_cte()
                        back_time()                  

                else:
                    back_cte()
                    back_time()



logger.info('======================================================')        


# with concurrent.futures.ThreadPoolExecutor() as executor:
#     executor.map(main, jingles)