#!/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 traceback
import time
import yaml
import mylibnetwork
lroot = logging.getLogger("root")
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"
)
group_af_family = parser.add_mutually_exclusive_group()
group_af_family.add_argument(
    "-u","--af-unix",
    dest="af_family",
    # default=False,
    action="store_const",
    const="AF_UNIX",
    help="""use an AF_UNIX socket (a file). can't be used in combination with
        --af-inet."""
    # " will be used \
    #     instead of an AF_INET socket (hostname/ip address + port)."
)
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"""
        # (hostname/ip address + port) will be used instead of an AF_INET \
        # socket (a file)."
)
args = parser.parse_args()
print(args)
if args.debug:
    with open("../../bee_logging.yaml") as f:
        data = f.read()
    config = yaml.safe_load(data)
    logging.config.dictConfig(config)
server = mylibnetwork.Server(
    host=args.host,
    port=args.port,
    af_family=args.af_family,
    handler=mylibnetwork.ConnHandlerEcho
)
try:
    server.run()
except KeyboardInterrupt:
    lroot.warn("KeyboardInterrupt, aborting!")
finally:
    pass