import argparse
import asyncio
from datetime import datetime, timedelta
import logging
import urllib.parse

from dateutil import parser, tz
import yaml
import zmq
import zmq.asyncio

async def auto_run(cfg):
    """
    Run the report service automatically depending on the scheduled times
    in the run_time list, read from the config yaml file (report_conf.yaml)
    """

    # time index that points at a timestamp, when the next
    # report service run takes place.
    tidx = 0

    # list of timestamps for the report service runs
    run_time = cfg['GLOBAL']['run-on']

    for i, ti in enumerate(run_time):
        run_time[i] = parser.parse(ti)

    while True:

        time_now = datetime.utcnow().replace(tzinfo=tz.tzutc())
        sched_time = run_time[tidx]

        if sched_time.tzinfo is None:
            sched_time = sched_time.replace(tzinfo=tz.tzutc())

        # do automatic-run.
        if time_now > sched_time:
            con = zmq.asyncio.Context()
            sock = con.socket(zmq.REQ)
            port = cfg['GLOBAL']['server-port']
            sock.connect(port)
            await sock.send_pyobj(['all'])
            msg = await sock.recv_pyobj()
            logging.info('{} Automatic Run'
                         .format(msg))

            # Changing run_time to the sametime next week
            run_time[tidx] = sched_time + timedelta(weeks=1)

            tidx = tidx + 1 if tidx != len(run_time)-1 else 0

        # check every 10mins, if there is 
        # a need for an automatic-run.
        await asyncio.sleep(600)


arg_parser = argparse.ArgumentParser(description='Automatic Launch')
arg_parser.add_argument('--config-file', type=str, default='./report_conf.yaml')
arg_parser.add_argument('--log-file', type=str, default='./report.log')
arg_parser.add_argument('--logging', type=str, default="INFO",
                    choices=['INFO', 'DEBUG', 'ERROR'])

if __name__ == "__main__":
    args = vars(arg_parser.parse_args())
    conf_file = args["config_file"]
    with open(conf_file, "r") as f:
        cfg = yaml.load(f.read())

    logfile = args["log_file"]
    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

    logging.basicConfig(filename=logfile, filemode='a+',
                        level=getattr(logging, args['logging']),
                        format='%(levelname)-6s: %(asctime)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    loop = asyncio.get_event_loop()
    loop.run_until_complete(auto_run(cfg))
    loop.close()