#!/usr/bin/env python3

# This is just a skeleton - code reads horiszons but need to be converted to do plotting

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

print("Code in progress")
sys.exit(1)

parser = argparse.ArgumentParser()
#parser.add_argument('-d', '--doublesideband', '-doublesideband', help="Double sideband", action="store_true")
#parser.add_argument('-p', '--plot', '-plot', help="Plot results", action="store_true")
parser.add_argument('-azel', '--azel', help="Output AzEl", 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):
  for i, value in enumerate(values):
    if value==name:
      return(i)
  print("Failed to fine '{}' 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', columns)
  if args.azel:
    iRA = findColumn('Azi_(a-app)', columns)
    iDec = findColumn('Elev_(a-app)', columns)
  else:
    iRA = findColumn('R.A._(ICRF)', columns)
    iDec = findColumn('DEC__(ICRF)', columns)


  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]
    RA = s[1]
    Dec = s[2]

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

    if (args.azel):
        print("{}-{}-{}T{} {} {}".format(y, m, day, t, RA, Dec))

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