from __future__ import print_function
import argparse
import json
import logging
import os
import sys
from .config import load_config, configuration_warnings
from .engine import Engine
from .outputs import switch_courtesy_tones, switch_id


def main(argv=None):
    parser = argparse.ArgumentParser(prog="br-skywarn", description="Control Bayou Radar Skywarn")
    parser.add_argument("--config", default=os.environ.get("BRS_CONFIG", "/etc/bayouradar-skywarn/config.yaml"))
    sub = parser.add_subparsers(dest="command")
    sub.add_parser("status")
    sub.add_parser("run-once")
    sub.add_parser("config-check")
    enabled = sub.add_parser("enabled")
    enabled.add_argument("value", choices=["true", "false", "toggle"])
    describe = sub.add_parser("describe")
    describe.add_argument("selector")
    announce = sub.add_parser("announce")
    announce.add_argument("text")
    tones = sub.add_parser("tones")
    tones.add_argument("mode", choices=["normal", "weather"])
    ids = sub.add_parser("id")
    ids.add_argument("mode", choices=["normal", "weather"])
    args = parser.parse_args(argv)
    if not args.command:
        parser.print_help()
        return 2
    cfg = load_config(args.config)
    logging.basicConfig(level=getattr(logging, str(cfg["app"].get("log_level", "INFO")).upper(), logging.INFO), format="%(levelname)s: %(message)s")
    engine = Engine(cfg)
    try:
        if args.command == "config-check":
            print("Configuration is valid: %s" % args.config)
            for warning in configuration_warnings(cfg):
                print("WARNING: %s" % warning)
        elif args.command == "status":
            status_path = os.path.join(cfg["app"]["runtime_dir"], "status.json")
            if os.path.exists(status_path):
                with open(status_path, "r") as handle:
                    output = json.load(handle)
            else:
                alerts = engine.state.get_alerts()
                output = {
                    "enabled": engine.enabled(),
                    "active_count": len(alerts),
                    "last_error": engine.state.get_meta("app.last_error"),
                    "alerts": [{"number": i + 1, "id": a.id, "event": a.event, "area": a.area_desc} for i, a in enumerate(sorted(alerts.values(), key=lambda x: (x.event, x.area_desc)))],
                }
            print(json.dumps(output, indent=2, sort_keys=True))
        elif args.command == "run-once":
            print(json.dumps(engine.cycle(), indent=2, sort_keys=True))
        elif args.command == "enabled":
            current = engine.enabled()
            value = (not current) if args.value == "toggle" else args.value == "true"
            engine.set_enabled(value)
            print("Bayou Radar Skywarn enabled: %s" % value)
        elif args.command == "describe":
            alert = engine.describe(args.selector)
            print("Announced description for %s (%s)" % (alert.event, alert.id))
        elif args.command == "announce":
            engine._speak(args.text, "manual")
            print("Announcement queued")
        elif args.command == "tones":
            print("Courtesy tone mode: %s" % switch_courtesy_tones(cfg["courtesy_tones"], engine.state.get_alerts(), args.mode))
        elif args.command == "id":
            print("ID mode: %s" % switch_id(cfg["id_change"], engine.state.get_alerts(), args.mode))
    finally:
        engine.close()
    return 0


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