from __future__ import print_function
import argparse
import logging
import os
import signal
import sys
import time
from .config import load_config
from .engine import Engine
from .webserver import start_web

STOP = False


def _stop(signum, frame):
    global STOP
    STOP = True


def configure_logging(level):
    logging.basicConfig(level=getattr(logging, str(level).upper(), logging.INFO), format="%(asctime)s %(levelname)s %(name)s: %(message)s")


def main(argv=None):
    parser = argparse.ArgumentParser(description="Bayou Radar Skywarn service")
    parser.add_argument("--config", default=os.environ.get("BRS_CONFIG", "/etc/bayouradar-skywarn/config.yaml"))
    parser.add_argument("--once", action="store_true")
    args = parser.parse_args(argv)
    cfg = load_config(args.config)
    configure_logging(cfg["app"].get("log_level", "INFO"))
    engine = Engine(cfg)
    package_dir = os.path.dirname(__file__)
    web = start_web(cfg["web"], cfg["app"]["runtime_dir"], package_dir)
    signal.signal(signal.SIGTERM, _stop)
    signal.signal(signal.SIGINT, _stop)
    try:
        if args.once:
            print(engine.cycle())
            return 0
        interval = max(30, int(cfg["app"].get("poll_seconds", 30)))
        while not STOP:
            started = time.time()
            try:
                engine.cycle()
            except Exception:
                logging.getLogger(__name__).exception("Cycle failed")
            delay = max(1, interval - (time.time() - started))
            end = time.time() + delay
            while not STOP and time.time() < end:
                time.sleep(min(1, end - time.time()))
        return 0
    finally:
        if web:
            web.shutdown()
        engine.close()


if __name__ == "__main__":
    sys.exit(main())
