#!/usr/bin/env python3

import argparse, sys, re
from astropy import units as u
from astropy.coordinates import Angle

parser = argparse.ArgumentParser()
parser.add_argument('-radec', '--radec', help="Output RaDec", action="store_true")
parser.add_argument('horizons')

args = parser.parse_args()

filename = args.horizons

reSOE = re.compile("\$\$SOE")
reEOE = re.compile("\$\$EOE")
reCutoff = re.compile(".*Elevation Cut-off Requested")
reTableFormat = re.compile("Table format")

count = -1

def findColumn(name, values):
  if not isinstance(name, (list, tuple)):
    name = [name] # Convert to list if scalar

  for i, value in enumerate(values):
    for n in name:
      if value.lower() == n.lower():
        return(i)
  print("Failed to find '{}' in {}".format(name,values))
  return(None)

sched = []

with open(filename, "r") as h:
  foundSOE = False
  foundEOE = False
  foundHeader = False
  for l in h:
    line = l.strip()

    if reTableFormat.match(line):
        count = 2
    elif reSOE.match(line):
        foundSOE = True
        break

    if count==0:
      columns = [x.strip() for x in line.split(",")]
    if count>=0:  count -= 1

  if not foundSOE:
    print('Failed to fine "$$SOE" section')
    sys.exit(1)

  iDate = findColumn(['Date__(UT)__HR:MN:SS','Date__(UT)__HR:MN'], columns)
  if not args.radec:
    iRA = findColumn(['Azi_(a-app)','Azimuth_(a-app)'], columns)
    iDec = findColumn(['Elev_(a-app)','Elevation_(a-app)'], columns)
  else:
    iRA = findColumn('R.A._(ICRF)', columns)
    iDec = findColumn('DEC__(ICRF)', columns)
    
  if iRA is None or iDec is None: exit(1)
    
  for l in h:
    line = l.strip()
    if line == "": continue
    if reCutoff.match(line): continue

    if reEOE.match(line):
        foundEOE = True
        break

    data = [x.strip() for x in line.split(",")]
    sched.append([data[iDate],data[iRA],data[iDec]])
    
  if not foundSOE:
    print('Failed to find "$$EOE"')
    sys.exit(1)

months = {
    'Jan': "01",
    'Feb': "02",
    'Mar': "03",
    'Apr': "04",
    'May': "05",
    'Jun': "06",
    'Jul': "07",
    'Aug': "08",
    'Sep': "09", 
    'Oct': "10",
    'Nov': "11",
    'Dec': "12"
}

for s in sched:
    date = s[0]
    left = s[1]
    right = s[2]

    (d, t) = date.split()
    (y, m, day) = d.split("-")
    m = months[m]

    if (not args.radec):
        print("{}-{}-{}T{} {} {}".format(y, m, day, t, left, right))

    else:
        RA = Angle(left, unit=u.hour).degree
        Dec = Angle(dight, unit=u.deg).degree
        print("{}-{}-{}T{} {:.8f} {:.8f}".format(y, m, day, t, RA, Dec))
