#!/usr/bin/env python3

import os
import psycopg2 as connector
from urllib.parse import urlparse
import json

DATABASE_URL = os.environ['DATABASE_URL']

dbUrl = urlparse(DATABASE_URL)

DATABASE_OPTIONS = {
    'user': dbUrl.username,
    'password': dbUrl.password,
    'host': dbUrl.hostname,
    'databaseName': dbUrl.path[1:],
    'tableName': 'signals'
}

print('Content-Type: application/json', end='\r\n\r\n')

try:
    dbConn = connector.connect(user=DATABASE_OPTIONS['user'], password=DATABASE_OPTIONS['password'],
                               host=DATABASE_OPTIONS['host'], database=DATABASE_OPTIONS['databaseName'])

    dbCursor = dbConn.cursor()

    sqlQueryString = 'SELECT signalid, latitude, longitude FROM ' + DATABASE_OPTIONS['tableName'] + ';'

    dbCursor.execute(sqlQueryString)

    data = []

    for (signalId, latitude, longitude) in dbCursor:
        data.append({
            'signalId': signalId,
            'coordinate': {
                'latitude': latitude,
                'longitude': longitude
            }
        })

    print(json.dumps(data))

    dbConn.close()

except Exception as exception:
    print(json.dumps({
        'error': 'Error occured.' + str(exception)
    }))
