import logging
import os
from pprint import pprint

import gpxpy
from lxml import etree
from lxml.etree import _ElementTree
from pykml.factory import KML_ElementMaker as KML
from pykml import parser


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


def create_placemark_from_gpx_file(gpx_file):
    coords = " ".join(export_coordinates_gpx_file(gpx_file))
    return KML.Placemark(
        KML.name(gpx_file.split('.', 1)[0]),
        KML.LineString(
            KML.coordinates(coords)
        ),
    ),


def create_kml_from_gpx_files(kml_file):
    pms = list()
    for filename in os.listdir(os.getcwd()):
        if filename.lower().endswith(".xml") or filename.lower().endswith(".gpx"):
            pms.append(create_placemark_from_gpx_file(filename))
    doc = KML.kml(KML.name("A third placemark!"),
                  set(pms))
    doc = KML.kml(KML.name("A third placemark!"))
    pprint(etree.tostring(doc, pretty_print=True, encoding='utf-8', method='xml').decode('utf-8'))
    with open(kml_file, "w") as f:
        f.write(etree.tostring(doc, pretty_print=True).decode('utf-8'))


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
