from xml.etree import ElementTree as ET
import sys
import sqlite_utils

KML = "{http://www.opengis.net/kml/2.2}"


def iterate_kml(filepath):
    fp = open(filepath)
    parser = ET.XMLPullParser(["end"])
    while True:
        chunk = fp.read(1024 * 8)
        parser.feed(chunk)
        for event, element in parser.read_events():
            assert event == "end"
            if element.tag == f"{KML}Placemark":
                name = element.find(f".//{KML}name").text
                description = 'soon'
                #description = element.find(f".//{KML}description").text
                longitude, latitude, unknown = map(
                    float, element.find(f".//{KML}coordinates").text.split(",")
                )
                yield {
                    "name": name,
                    "x": latitude,
                    "y": longitude,
                    "description": description,
                }
        if not chunk:
            break


if __name__ == "__main__":
    db = sqlite_utils.Database("fountains.db")
    db["locations"].insert_all(iterate_kml(sys.argv[-1]))