#!/usr/bin/env python3

import argparse, re, time, logging, sys
from datetime import datetime
from legacyserver import LegacyServer
server = 'bigrock.atnf.csiro.au'
port = 2334

parser = argparse.ArgumentParser()

parser.add_argument('sched', help="Schedule paddle scans")
args = parser.parse_args()

fsched = args.sched;

commentRE = re.compile(r'^([^#]*)#(.*)$')

#logging.Formatter.converter = lambda *args: datetime.datetime.now(tz=timezone('UTC')).timetuple()
log = logging.getLogger('main')

# Root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)

# Console output
console = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)-5s - %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
root_logger.addHandler(console)

# Logfile output
file_logger = logging.FileHandler('mopraPaddle.log')
formatter = logging.Formatter('%(asctime)s: %(name)-9s - %(levelname)-5s - %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
file_logger.setFormatter(formatter)
file_logger.setLevel(logging.DEBUG)
root_logger.addHandler(file_logger)

# Read schedule file

now =  datetime.utcnow()

first = True
scans = []
with open(fsched) as file:
    for l in file:
        line = l.strip()

        # Skip comments
        m = commentRE.match(line)
        if m: line = m.group(1)
            
        # Skip blank lines
        if line.isspace() or line=="":
            continue
            
        (date, t, dur) = line.split()
        thistime = datetime.fromisoformat(date+' '+t)
        if (now>thistime):
            if first:
                log.info("Schedule already started, skipping initial scans")
                first = False
            continue
        scans.append((thistime, float(dur)))

if len(scans)==0:
    log.warning("Schedule already finished")
    sys.exit(1)

## Connect to antenna

ls = LegacyServer((server,port))
ls.connect()
ls.allocate()
    
for s in scans:
    now =  datetime.utcnow()
    wait = (s[0]-now).total_seconds()
    if wait>0: log.info("Waiting till {}".format(s[0].strftime("%H:%M:%S")))
    while wait>0:
        time.sleep(wait/2.0)
        now = datetime.utcnow()
        wait = (s[0]-now).total_seconds()
    log.info("Inserting Paddle")
    ls.noiscl(paddle=True)
    time.sleep(s[1])
    log.info("Removing Paddle")
    ls.noiscl(paddle=False)
        
    

