#!/usr/bin/env python3

# Copyright 2017 CodiLime
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import logging
import asyncio
import importlib
import signal

from veles.async_client.conn import AsyncRemoteConnection
from veles.async_client import proto
from veles.util import helpers

parser = argparse.ArgumentParser(
    parents=[helpers.get_client_argparse(), helpers.get_logging_argparse()],
    add_help=False)
parser.add_argument('--plugin', action='append',
                    help='name plugin module to load')
args = parser.parse_args()

logging.basicConfig(level=logging.getLevelName(args.log_level))

logging.info('Świtezianka plugin is starting up...')
loop = asyncio.get_event_loop()

proto = loop.run_until_complete(proto.create_client(loop, args.server_url))[1]
conn = AsyncRemoteConnection(loop, proto)

logging.info('Loading plugins...')
if args.plugin is not None:
    for pname in args.plugin:
        logging.info('{}...'.format(pname))
        mod = importlib.import_module('veles.plugins.' + pname)
        conn.register_plugin(mod)

logging.info('Ready.')
try:
    loop.add_signal_handler(signal.SIGINT, loop.stop)
except NotImplementedError:
    pass
loop.run_forever()
logging.info('Goodbye.')
