#!python
import asyncio as aio
from pathlib import Path
from argparse import ArgumentParser, RawTextHelpFormatter
from configparser import ConfigParser
import logging

from truhanen.serobot.web import SerobotServer


# Module-level logger
logger = logging.getLogger(__name__)


def configure_logging(level: str):
    logging_format = '{levelname}|{asctime}|{name}|{funcName}|{message}'
    logging.basicConfig(format=logging_format, level=level, style='{')


def parse_arguments():
    argument_parser = ArgumentParser(formatter_class=RawTextHelpFormatter)

    argument_parser.add_argument(
        'config_file', nargs='?', type=Path,
        help='A configuration file that lists the other path arguments.\n'
             'See README.md for details.')
    argument_parser.add_argument(
        '-a', '--auth-file', type=Path,
        help='A file that lists the authorized users and passwords.\n'
             'See README.md for details.')
    argument_parser.add_argument(
        '-c', '--ssl-certfile', type=Path,
        help='Path to a SSL certificate file for HTTPS, .pem')
    argument_parser.add_argument(
        '-k', '--ssl-keyfile', type=Path,
        help='Path to a SSL key file for HTTPS, .pem')
    argument_parser.add_argument(
        '-l', '--log-level', default='INFO',
        help='The desired logging level as a name supported by the Python\'s\n'
             'built-in logging module. Defaults to INFO.')

    arguments, _ = argument_parser.parse_known_args()
    arguments = vars(arguments)

    # Update the values in arguments with the contents
    # of a config file, if given.
    config_path = arguments.pop('config_file')
    if config_path is not None:
        config = ConfigParser()
        config.read(config_path)
        # At the moment all variables in the .conf file are path-like,
        # so convert them blindly to Path objects.
        arguments.update({
            name: Path(value) for (name, value) in config.items('config')})

    return arguments


def main():
    arguments = parse_arguments()
    configure_logging(arguments.pop('log_level'))
    logger.info(f'Starting SerobotServer with arguments {arguments}')
    server = SerobotServer(**arguments)
    aio.run(server.start())


if __name__ == '__main__':
    main()
