#!/usr/bin/python3


# simple test program to generate synthetic bus position
# data (AVLS)

import json
import sys
import time
import math

import ridelogic_avls as rl

if len(sys.argv) < 3:
  print("provide path and stop geojson files")
  sys.exit(0)

json_path_fn = sys.argv[1]
json_stop_fn = sys.argv[2]

json_path = {}
json_stop = {}


with open(json_path_fn) as fp:
  json_path = json.loads(fp.read())

with open(json_stop_fn) as fp:
  json_stop = json.loads(fp.read())

_path = json_path["features"][0]["geometry"]["coordinates"]

bus_ctx = {
  "update_freq" : 1000,
  "gps_path": _path,
  "bus": [
    {
      "id": "bus0",
      "idx" : 0,
      "idx_dir" : 1,
      "bearing":0,
      "longitude": _path[0][0],
      "latitude": _path[0][1]
    },
    {
      "id":"bus1",
      "idx": len(_path)-1,
      "idx_dir" : -1,
      "bearing":0,
      "longitude": _path[-1][0],
      "latitude": _path[-1][1]
    }
  ]
}

while True:

  feed_msg = {
    "header" : { "gtfs_realtime_version":"2.0", "timestamp":int(time.time()) },
    "entity":[]
  }



  for bus in bus_ctx["bus"]:

    print(bus["id"], bus["longitude"], bus["latitude"], bus["bearing"])

    lng_prv = bus["longitude"]
    lat_prv = bus["latitude"]


    bus["longitude"] = bus_ctx["gps_path"][bus["idx"]][0]
    bus["latitude"] = bus_ctx["gps_path"][bus["idx"]][1]
    bus["idx"] += bus["idx_dir"]
    if bus["idx"] < 0:
      bus["idx"] = 0
      bus["idx_dir"] = 1
    if bus["idx"] >= len(bus_ctx["gps_path"]):
      bus["idx"] = len(bus_ctx["gps_path"])-1
      bus["idx_dir"] = -1

    lng_cur = bus["longitude"]
    lat_cur = bus["latitude"]

    bus["bearing"] = int(180.0 * math.atan2(lng_cur - lng_prv, lat_cur - lat_prv) / math.pi)

    entity = {
      "id" : bus["id"],
      "vehicle" : {
        "position" : {
          "longitude":lng_cur,
          "latitude":lat_cur,
          "bearing":bus["bearing"]
        }
      }
    }

    feed_msg["entity"].append(entity);


  rl.write_protobuf("test_gtfs.pb", feed_msg)

  time.sleep( float(bus_ctx["update_freq"])/1000.0 )
