import gpxpy
import gpxpy.gpx
import os
import logging


def export_coordinates_gpx_file_as_string(file, prepend_file_name=False):
    gpx_file = open(file, "r")
    logging.info(f"opening {gpx_file}")
    gpx = gpxpy.parse(gpx_file)

    str = "<LineString><coordinates>"
    if prepend_file_name:
        if "_" in file:
            str = file.split(".")[0].split("_")[1] + "\t" + "<LineString><coordinates>"
        else:
            str = file.split(".")[0] + "\t" + "<LineString><coordinates>"
    for track in gpx.tracks:
        for segment in track.segments:
            for point in segment.points:
                str = str + "{0},{1} ".format(round(point.longitude, 6), round(point.latitude, 6))

    return str + "</coordinates></LineString>"


def insert_coordinates_into_kml_file(kml_file, search_string, coordinate_string, backup_orig_file=True):
    with open(kml_file) as f:
        text = f.read()
    if backup_orig_file:
        if not os.path.exists("backup_" + kml_file):
            with open("backup_" + kml_file, "w") as f:
                f.write(text)
    found_idx = None
    splitted_text = text.splitlines()
    for i, l in enumerate(splitted_text):
        if "name=\"id\"" in l and str(search_string) in l:
            found_idx = i
            break
    if found_idx is not None:
        if "<LineString>" in splitted_text[found_idx + 2]:
            splitted_text[found_idx + 2] = coordinate_string
            text = "\n".join(splitted_text)
            with open(kml_file, 'w') as f:
                f.write(text)


for filename in os.listdir(os.getcwd()):
    if filename.lower().endswith(".xml") or filename.lower().endswith(".gpx"):
        coords_string = export_coordinates_gpx_file_as_string(filename)
        insert_coordinates_into_kml_file("europa_testkarte.kml", filename.split('.', 1)[0], coords_string)
exit()


def export_coordinates_gpx_file(file):
    gpx_file = open(file, "r")
    logging.info(f"opening {gpx_file}")
    gpx = gpxpy.parse(gpx_file)

    coords = list()
    for track in gpx.tracks:
        for segment in track.segments:
            for point in segment.points:
                coords.append("{0},{1} ".format(round(point.longitude, 6), round(point.latitude, 6)))

    return coords
