#!/usr/bin/python3

import requests
import json

cameras = []

res = requests.get("https://tmc.deldot.gov/json/videocamera.json")
res.raise_for_status()
# {
#   "timestamp": "2024-02-03T09:00:50Z",
#   "timestampMS": "1706950850013",
#   "version": "1.1",
#   "uid": "-8569684966613574390",
#   "status": "normal",
#   "message": "",
#   "cameraCount": 282,
#   "cameraHash": "-1859423038",
#   "videoCameras": [
#     {
#       "urls": {
#         "rtmp": "rtmpt://167.21.72.35:80/live/KCAM001.stream",
#         "rtsp": "rtsp://167.21.72.35:554/live/KCAM001.stream",
#         "f4m": "http://167.21.72.35:1935/live/KCAM001.stream/manifest.f4m",
#         "m3u8": "http://167.21.72.35:1935/live/KCAM001.stream/playlist.m3u8",
#         "m3u8s": "https://video.deldot.gov:443/live/KCAM001.stream/playlist.m3u8",
#         "mssmooth": "http://167.21.72.35:1935/live/KCAM001.stream/Manifest"
#       },
#       "id": "KCAM001",
#       "title": "DE 1 @ MILFORD NECK ROAD (NORTH OFF)",
#       "county": "Kent",
#       "lat": 38.990771,
#       "lon": -75.448487,
#       "hash": "966393601",
#       "enabled": true
#     },
#     ...

for c in res.json()['videoCameras']:
    try:
        if not c['enabled']:
            print("warn: camera disabled; ignoring:", c)
            continue
        if not c['urls']['m3u8s'].startswith('https://'):
            raise Exception("invalid hlsUrl")
        cameras.append({
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [c['lon'], c['lat']], # yes, [lon, lat] since it's [x, y]
            },
            "properties": {
                "name": c['title'],
                "views": [
                    {
                        'hasVideo': True,
                        'src': c['urls']['m3u8s'],
                    },
                    # {
                    #     'hasVideo': False,
                    #     'src': c['imageUrl'],
                    # }
                ]
            },
        })
    except Exception as e:
        print(c)
        raise e

geojson = {
    "type": "FeatureCollection",
    "features": cameras,
}

with open("data.geojson", "w") as f:
    f.write(json.dumps(geojson))

print(f"{len(cameras)} locations found")