#!/usr/bin/env python
"""
ELIQ Online

Usage:
  eliq (-h | --help)
  eliq --version
  eliq [-v|-vv] [options] now
  eliq [-v|-vv] [options] today
  eliq [-v|-vv] [options] week
  eliq [-v|-vv] [options] month
  eliq [-v|-vv] [options] year

Options:
  -t <token>      Access token
  -h --help       Show this message
  -v,-vv          Increase verbosity
  -d              Debug
  --version       Show version
"""

import docopt
import logging
from sys import stderr
from os.path import join, expanduser
from os import environ as env
from yaml import safe_load as load_yaml
from datetime import datetime, timedelta
from aiohttp import ClientSession

from eliqonline import API, __version__

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


# $HOME/.eliqonline and $HOME/.config/eliqonline.conf
CONFIG_FILES = (
    (expanduser("~"), ".eliqonline"),
    (
        env.get("XDG_CONFIG_HOME", join(expanduser("~"), ".config")),
        "eliqonline.conf",
    ),
)


def read_config():
    for directory, filename in CONFIG_FILES:
        try:
            config = join(directory, filename)
            with open(config) as config:
                _LOGGER.debug("Found config file %s", config.name)
                return load_yaml(config)
        except (IOError, OSError):
            continue
    return {}


async def main(args, config):
    access_token = args.get("-t") or config.get("accesstoken")

    async with ClientSession() as session:
        api = API(session=session, access_token=access_token)
        if args["now"]:
            result = await api.get_data_now()
            print("Current power: %d w" % result["power"])
            return

        now = datetime.now()
        if args["today"]:
            intervaltype = api.INTERVAL_6MIN
            startdate = datetime(year=now.year, month=now.month, day=now.day)
            enddate = datetime(
                year=now.year,
                month=now.month,
                day=now.day,
                hour=23,
                minute=59,
                second=59,
            )
        else:
            intervaltype = api.INTERVAL_DAY
            enddate = now
            if args["week"]:
                startdate = datetime(
                    year=now.year, month=now.month, day=now.day
                ) - timedelta(days=7)
            elif args["month"]:
                startdate = datetime(year=now.year, month=now.month, day=1)
            elif args["year"]:
                startdate = datetime(year=now.year, month=1, day=1)

        result = await api.get_data(
            startdate=startdate, enddate=enddate, intervaltype=intervaltype
        )

        for item in result["data"]:
            print(
                "%s - %s: average power: %4s W"
                % (
                    item["time_start"],
                    item["time_end"],
                    str(int(item["avgpower"])) if item["avgpower"] else "?",
                )
            )


if __name__ == "__main__":
    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"]]

    logging.basicConfig(
        level=log_level, stream=stderr, datefmt=DATEFMT, format=LOGFMT
    )

    config = read_config()

    try:
        from asyncio import run
    except ImportError:
        _LOGGER.debug("Pre 3.7 patch")

        def run(fut, debug=False):
            # pre 3.7
            loop = asyncio.get_event_loop()
            loop.set_debug(debug)
            loop.run_until_complete(fut)
            loop.close()

    try:
        run(main(args, config), debug=debug)
    except KeyboardInterrupt:
        pass
