#! /usr/bin/python3 -s
# -*- coding: utf-8 -*-

import asyncio
import aiohttp
import gbulb
from configparser import ConfigParser
from pathlib import Path
import logging
import argparse

from rauc_hawkbit.rauc_dbus_ddi_client import RaucDBUSDDIClient


def result_callback(result):
    print("Result:   {}".format('SUCCESSFUL' if result == 0 else 'FAILED' ))

def step_callback(percentage, message):
    print("Progress: {:>3}% - {}".format(percentage, message))

async def main():
    # config parsing
    config = ConfigParser()
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-c',
        '--config',
        type=str,
        help="config file")
    parser.add_argument(
        '-d',
        '--debug',
        action='store_true',
        default=False,
        help="enable debug mode"
    )

    args = parser.parse_args()

    if not args.config:
        args.config = 'config.cfg'

    cfg_path = Path(args.config)

    if not cfg_path.is_file():
        print("Cannot read config file '{}'".format(cfg_path.name))
        exit(1)

    config.read_file(cfg_path.open())

    try:
        LOG_LEVEL = {
            'debug': logging.DEBUG,
            'info': logging.INFO,
            'warn': logging.WARN,
            'error': logging.ERROR,
            'fatal': logging.FATAL,
        }[config.get('client', 'log_level').lower()]
    except Exception:
        LOG_LEVEL = logging.INFO

    HOST = config.get('client', 'hawkbit_server')
    SSL = config.getboolean('client', 'ssl')
    TENANT_ID = config.get('client', 'tenant_id')
    TARGET_NAME = config.get('client', 'target_name')
    AUTH_TOKEN = config.get('client', 'auth_token')
    ATTRIBUTES = {'MAC':config.get('client', 'mac_address')}
    BUNDLE_DL_LOCATION = config.get('client', 'bundle_download_location')

    if args.debug:
        LOG_LEVEL = logging.DEBUG


    logging.basicConfig(level=LOG_LEVEL,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    async with aiohttp.ClientSession() as session:
        client = RaucDBUSDDIClient(session, HOST, SSL, TENANT_ID, TARGET_NAME,
                                   AUTH_TOKEN, ATTRIBUTES, BUNDLE_DL_LOCATION,
                                   result_callback, step_callback)
        await client.start_polling()

if __name__ == '__main__':
    # create event loop, open aiohttp client session and start polling
    gbulb.install()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
