#!/usr/bin/python3

# This file has been replaced by ODKParsers(), and will be delete in the next release.

#
#   Copyright (C) 2023, 2024 Humanitarian OpenstreetMap Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

import argparse
import logging
import os
import re
import sys
from datetime import datetime
from pathlib import Path

import flatdict
import xmltodict
from geojson import Feature, FeatureCollection, dump
from shapely.geometry import Point

# Instantiate logger
log = logging.getLogger(__name__)


def main():
    """This is a program that reads in the ODK Instance file, which is in XML,
    and converts it to a GeoJson file so it can be viewed in an editor.
    """
    parser = argparse.ArgumentParser(description="Convert ODK XML instance file to GeoJson")
    parser.add_argument("-v", "--verbose", nargs="?", const="0", help="verbose output")
    parser.add_argument("-i", "--instance", required=True, help="The instance file(s) from ODK Collect")
    parser.add_argument("-o", "--outfile", default="tmp.geojson", help="The output file for JOSM")
    args = parser.parse_args()

    # if verbose, dump to the terminal
    if args.verbose is not None:
        logging.basicConfig(
            level=logging.DEBUG,
            format=("%(threadName)10s - %(name)s - %(levelname)s - %(message)s"),
            datefmt="%y-%m-%d %H:%M:%S",
            stream=sys.stdout,
        )

    xmlfiles = list()
    if args.instance.find("*") >= 0:
        toplevel = Path()
        unesc = args.instance.replace("\\", "")
        for directory in toplevel.glob(unesc):
            if directory.is_dir():
                xml = os.listdir(directory)
                # There is always only one XML file per instance
                full = os.path.join(directory, xml[0])
            xmlfiles.append(full)
    else:
        toplevel = Path(args.instance)
        if toplevel.is_dir():
            # There is always only one XML file per instance
            full = os.path.join(toplevel, os.path.basename(toplevel))
            xmlfiles.append(full + ".xml")
        else:
            xmlfiles.append(args.instance)

    # print(xmlfiles)

    # These are all generated by Collect, and can be ignored
    features = list()
    for xml in xmlfiles:
        print("Processing instance file: %s" % xml)
        # odkxml = ODKInstance()
        # data = odkxml.parse(filespec=xml)
        file = open(xml, "r")
        # Instances are small, read the whole file
        data = file.read(os.path.getsize(xml))
        doc = xmltodict.parse(data)

        flattened = flatdict.FlatDict(doc["data"])
        poi = Point()
        feature = dict()
        for key, value in flattened.items():
            if key[0] == "@" or value is None:
                continue
            last = key.rfind(":") + 1
            key = key[last:]
            pat = re.compile("[0-9.]* [0-9.-]* [0-9.]* [0-9.]*")
            gps = re.findall(pat, value)
            if len(gps) > 0:
                tmp = gps[0].split(" ")
                lat = float(tmp[0])
                lon = float(tmp[1])
                poi = Point(lon, lat)
            else:
                feature[key] = value
        features.append(Feature(geometry=poi, properties=feature))
    collection = FeatureCollection(features)

    now = datetime.now()
    timestamp = f"_{now.year}_{now.month}-{now.day}-{now.hour}-{now.minute}"
    # outfile = args.instance.replace("*", "") + timestamp + ".geojson"
    # outfile = outfile.replace(" ", "")
    fout = open(args.outfile, "w")
    dump(collection, fout)

    print(f"Wrote output file {args.outfile}")


if __name__ == "__main__":
    """This is just a hook so this file can be run standlone during development."""
    main()
