import pysrt
import csv
from math import radians, cos, sin, asin, sqrt


def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    return c * r


#100ms=0.1sec

#file to write output i.e images at every second
file_ans=open('path for output file','w')

# reading srt file
subs = pysrt.open('path for srt file', encoding='iso-8859-1')

#length of subtitle file (no of subtitiles)
len_srt=len(subs)

#change distance as per your choice
near_by=0.035 #give in kilometers

#generated csv file using exifread (to read meta data of photos )
img_file=open('path of file which was generated by running metadata_extract','r')


#set to store images
k=set()


#dont change anything below this line
#########################################################################################
file=img_file.read()
list_img=file.split(',')
file_ans.write(str("Start time")+","+str("End time")+","+str("images")+"\n")
count=0


for i in range(0,len_srt):

    cot=0
    for o in range(0,(len(list_img)),3):
            cot+=1
            srt=str(subs[i].text)
            srt_long = srt.split(',')[0]
            srt_lat = srt.split(',')[1]

            img_lat=list_img[o]
            img_long=list_img[o+1]
            img_img=list_img[o+2]

            ans=haversine(float(srt_long),float(srt_lat),float(img_long),float(img_lat))
            #print (ans)
            if ans<=near_by:
                #print(ans)

                k.add(img_img)
                #print(img_img)

    if count%10==9 :
        file_ans.write(str(int(count/10))+","+str(int(((count+1)/10)))+","+"\n")
        for each in k:
            file_ans.write(","+","+each+"\n")

        k.clear()
    count = count + 1
    print(cot)
#########################################################################################

print("sucess")
