import Foundation

enum GPXExporter {
    /// Writes the route to a temporary `.gpx` file and returns its URL.
    static func write(detail: RouteDetail) -> URL? {
        let xml = generate(detail: detail)
        let safeName = detail.name
            .replacingOccurrences(of: "/", with: "-")
            .trimmingCharacters(in: .whitespacesAndNewlines)
        let filename = safeName.isEmpty ? "tour" : safeName
        let url = FileManager.default.temporaryDirectory
            .appendingPathComponent("\(filename).gpx")
        do {
            try xml.write(to: url, atomically: true, encoding: .utf8)
            return url
        } catch {
            return nil
        }
    }

    static func generate(detail: RouteDetail) -> String {
        let trkpts = detail.gpsTrack.map { p -> String in
            if let alt = p.alt {
                return "      <trkpt lat=\"\(p.lat)\" lon=\"\(p.lon)\"><ele>\(alt)</ele></trkpt>"
            } else {
                return "      <trkpt lat=\"\(p.lat)\" lon=\"\(p.lon)\"/>"
            }
        }.joined(separator: "\n")

        let safeName = detail.name
            .replacingOccurrences(of: "&", with: "&amp;")
            .replacingOccurrences(of: "<", with: "&lt;")
            .replacingOccurrences(of: ">", with: "&gt;")

        return """
        <?xml version="1.0" encoding="UTF-8"?>
        <gpx version="1.1" creator="Ban Yaro Go" xmlns="http://www.topografix.com/GPX/1/1">
          <trk>
            <name>\(safeName)</name>
            <trkseg>
        \(trkpts)
            </trkseg>
          </trk>
        </gpx>
        """
    }
}
