#!/usr/bin/env python3.5
# Copyright 2017 Digital
#
# This file is part of DigiLib.
#
# DigiLib is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DigiLib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with DigiLib.  If not, see <http://www.gnu.org/licenses/>.
import argparse
import logging
import logging.config
import logging.handlers
import sys
import threading
import traceback
import time
import yaml
import mylibnetwork

lroot = logging.getLogger("root")

def user_input():
    while True:
        data = input("type something:")
        client.send(data)

def configure_logging():
    with open("../../bee_logging.yaml") as f:
        data = f.read()
    config = yaml.safe_load(data)
    logging.config.dictConfig(config)

parser = argparse.ArgumentParser(description="BeeWatch Server",)
parser.add_argument("host",type=str,
    help="hostname/ip address/filename (only if --use-file was specified)")
parser.add_argument("port",type=int,default=80540,nargs="?",
    help="""the port on wich the connection will open up. ignored if --use-file
         is given""")
parser.add_argument("-d","--debug",default=False,action="store_true",
    help="enables logging")
parser.add_argument("-a","--async_client",default=False,action="store_true",
    help="Use an asynchronous client instead of a threaded one")
group_af_family = parser.add_mutually_exclusive_group()
group_af_family.add_argument(
"-u","--af-unix",
    dest="af_family",
    action="store_const",
    const="AF_UNIX",
    help="""use an AF_UNIX socket (a file). can't be used in combination with
        --af-inet."""
)
group_af_family.add_argument(
    "-i","--af_inet",
    default="AF_INET",
    dest="af_family",
    action="store_const",
    const="AF_INET",
    help="""use an AF_INET socket (hostname/ip address + port). can't be used
        with --af-unix"""
)
args = parser.parse_args()
if args.debug:
    configure_logging()
if args.async_client:
    client_class = mylibnetwork.AsyncClient
else:
    client_class = mylibnetwork.Client
client = client_class(
    host=args.host,
    port=args.port,
    af_family=args.af_family,
)
input_thread = threading.Thread(target=user_input,daemon=True)
try:
    input_thread.start()
    if args.async_client:
        client.run(connect=True)
    else:
        client.start()
        client.connect()
    while True:
        client.join(1)
        if not client.is_running():
            break
except KeyboardInterrupt:
    print("\r    ", end="\r")
    lroot.warn("KeyboardInterrupt, aborting!")
finally:
    client.stop()