import sys
import time

import geopy.distance

import requests
from dse_shared_libs import daf, traffic_light_state, traffic_light_color, target_velocity

from devices.traffic_light import TrafficLight
from devices.vehicle import Vehicle

sys.modules['daf'] = daf
sys.modules['traffic_light_state'] = traffic_light_state
sys.modules['traffic_light_color'] = traffic_light_color
sys.modules['target_velocity'] = target_velocity

"""
USED AS ENTRYPOINT FOR DOCKERFILE
Start all vehicles / traffic lights here
"""

if __name__ == '__main__':
    ENTITY_IDENT_URL = 'http://entityident:5002/api/v1/resources/'
    available = False
    while not available:
        try:
            response = requests.get(ENTITY_IDENT_URL + 'cars')
            cars = response.json()

            response = requests.get(ENTITY_IDENT_URL + 'traffic_lights')
            traffic_lights = response.json()
        except requests.exceptions.ConnectionError as e:
            print("Is the entity_ident_server running and reachable?")
            continue
        available = True

    for traffic_light in traffic_lights['cursor']:
        print(traffic_light)
        TrafficLight(tlid=traffic_light['id'],
                     switching_time=traffic_light['switchingTime']).start()
        time.sleep(0.5)

    for index, car in enumerate(cars['cursor']):
        print(car)
        # Get location of first TL
        tl_1_loc = geopy.Point(47.89584, 16.20719)
        # Calculate starting point by going south of TL_location the amount specified in cars.json
        d = geopy.distance.distance(kilometers=car['startingDistance'] / float(1000))
        starting_point = d.destination(point=tl_1_loc, bearing=182)
        starting_velocity = car['startingVelocity']
        print('StartingPoint is {} and startingVelocity is {}'.format(starting_point, starting_velocity))
        Vehicle(vin=car['vin'], starting_point=starting_point, starting_velocity=starting_velocity).start_driving()
        # Sleep for amount of seconds defined in second car before second car starts
        if len(cars['cursor']) > 1 and index < len(cars['cursor']) - 1:
            time.sleep(cars['cursor'][index + 1]['startingTime'])
