#!/usr/bin/python
import argparse
import sys

import requests


def horizons_api(start_time='2021-10-11 08:00', stop_time='2021-10-11 10:00', spacecraft='-41', station='75'):
    fd = f"!$$SOF\n \
        COMMAND= {spacecraft} \
        OBJ_DATA='YES' \
        MAKE_EPHEM='YES' \
        TABLE_TYPE='OBSERVER' \
        CENTER={station} \
        START_TIME={start_time} \
        STOP_TIME={stop_time} \
        STEP_SIZE='20 m' \
        QUANTITIES='1,4,18,20,23,24'"

    print(fd)
    return fd

# Define the new Horizons http address
url = 'https://ssd.jpl.nasa.gov/api/horizons_file.api'

start_time = "\'2021-10-11 08:00\'"
stop_time = "\'2021-10-11 10:00\'"
spacecraft = "\'-41\'"
station = "\'75\'"

fd = horizons_api(start_time, stop_time, spacecraft, station)
# Request the information via the Horizons API
r = requests.post(url, data={'format':'text'}, files={'input': fd})

print(r.text)
valid = 0
for line in r.text.split('\n'):
    if line == '$$SOE':
        valid = 1
        #val_line += 1
        #print(val_line)
    elif line == '$$EOE':
        valid = 0
        #print(val_line)
    #else:
        # invalid line
        #inv_line += 1
    
    if valid and line != '$$SOE':
        # save line
        clean_line = list(filter(None,line.split(' ')))
        #output_str = f"| {session:3d} | {a[0]} | 00:00-02:00 |  {session_id}  | {station}   | NNO | {float(a[4]):7.3f} | {float(a[6]):6.3f} | {float(a[2]):7.4f} | S       |  MEX                            |"
        epoch = clean_line[0]
        scan_time = clean_line[1]
        rah = clean_line[3]; ram = clean_line[4]; ras = clean_line[5]
        dech = clean_line[6]; decm = clean_line[7]; decs = clean_line[8]
        azimuth = clean_line[9]; elevation = clean_line[10]
        distance = clean_line[11]
        sot = clean_line[13]
        sto = clean_line[15]
        print(f'{epoch} {start_time} {rah} {ra} {ras}')