import os
import csv
from PIL import Image
from tqdm import tqdm
import math
import exif
import simplekml

FOLDER_PATH = "merged/"
colordict = []
kml=simplekml.Kml()

def main():
    pbar1 = tqdm(total=len(os.listdir(FOLDER_PATH)), unit='files', position=0)
    pbar1.set_description("Progress")
    pbar2 = tqdm(total=19961856, unit='pixels', position=1) # mighty sus
    
    with open('autoGCP_out.csv', 'w', newline='') as csvfile:
        fieldnames = ['filename', 'x_pixel', 'y_pixel', 'gps-lat', 'gps-long']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        
        for filename in os.listdir(FOLDER_PATH):
            colordict = []
            pbar2.set_description(filename)
            pbar2.update(-1 * pbar2.n)
            f = os.path.join(FOLDER_PATH, filename)
            # checking if it is a file
            if os.path.isfile(f):
                try:
                    im=Image.open(f)

                    with open(f, 'rb') as src:
                        img = exif.Image(src)

                    coords = (decimal_coords(img.gps_latitude,
                        img.gps_latitude_ref),
                        decimal_coords(img.gps_longitude,
                        img.gps_longitude_ref))

                    t_im=im.convert("RGB")
                    for x in range(t_im.width):
                        for y in range(t_im.height):
                            pbar2.update(1)
                            o_check = check_for_red(t_im.getpixel((x,y)), x,y)
                            if o_check:
                                
                                writer.writerow({'filename': filename, 'x_pixel': str(x), 'y_pixel': str(y), 'gps-lat': coords[0], 'gps-long': coords[1]})
                                kml.newpoint(name=filename, coords=[(coords[1],coords[0])])
                except IOError:
                    pass
            pbar1.update(1)
        
        kml.save('autoGCP_out.kml')


def check_for_red(color, x, y):
    color_r = color[0]
    color_g = color[1]
    color_b = color[2]
    if color_r > 250 and color_b < 200 and color_g < 200:
        unique_flag = True
        for detected in colordict:
            if math.dist(detected, [x,y]) < 20:
                unique_flag = False
        
        if unique_flag:
            colordict.append([x,y])
            return True
    
    return False

def decimal_coords(coords, ref):
    decimal_degrees = coords[0] + coords[1] / 60 + coords[2] / 3600
    if ref == 'S' or ref == 'W':
        decimal_degrees = -decimal_degrees
    return decimal_degrees

main()
