#!/usr/bin/env python3
# -*- mode: python; coding: utf-8 -*-
"""
Retrieve information from your toothbrush

Usage:
  toothbrush (-h | --help)
  toothbrush --version
  toothbrush [-v|-vv] [options] scan
  toothbrush [-v|-vv] [options] monitor <mac>

Options:
  -i <interface>   Bluetooth adapter interface
  -h --help        Show this message
  -v,-vv           Increase verbosity
  -d               More debugging
  --version        Show version
"""

import docopt
import logging
import asyncio
from time import time
from json import dumps as to_json
from sys import stderr
from collections import OrderedDict
from datetime import timezone
import subprocess
import json
import blus
from toothbrush import parse, __version__

_LOGGER = logging.getLogger(__name__)

LOGFMT = "%(asctime)s %(levelname)5s (%(threadName)s) [%(name)s] %(message)s"
DATEFMT = "%y-%m-%d %H:%M.%S"

TOOTHBRUSH_ID = "Oral-B"


def main():
    """Command line interface."""
    args = docopt.docopt(__doc__, version=__version__)

    debug = args["-d"]

    if debug:
        log_level = logging.DEBUG
    else:
        log_level = [logging.ERROR, logging.INFO, logging.DEBUG][args["-v"]]

    try:
        import coloredlogs

        coloredlogs.install(
            level=log_level, stream=stderr, datefmt=DATEFMT, fmt=LOGFMT
        )
    except ImportError:
        _LOGGER.debug("no colored logs. pip install coloredlogs?")
        logging.basicConfig(
            level=log_level, stream=stderr, datefmt=DATEFMT, format=LOGFMT
        )

    logging.captureWarnings(debug)

    if debug:
        _LOGGER.info("Debug is on")

    class Observer(blus.DeviceObserver):
        def discovered(self, path, device):
            pass

        def seen(self, path, device):
            alias = device.get("Alias")
            _LOGGER.info("Seeing %s", alias)

            if TOOTHBRUSH_ID not in alias:
                return

            if args["-d"]:
                for k, v in device.items():
                    _LOGGER.debug("%12s = %s", k, v)

            if args["scan"]:
                print(device.get("Name"), device.get("Address"), flush=True)
            elif args["monitor"]:
                print(json.dumps(parse(device)), flush=True)

    try:
        blus.scan(blus.DeviceManager(Observer()), transport="le")
    except KeyboardInterrupt:
        _LOGGER.info("Exiting")


if __name__ == "__main__":
    main()
