#!/usr/bin/env python3.5
# Copyright 2017 Digital
#
# This file is part of BeeWatch.
#
# BeeWatch 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.
#
# BeeWatch 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 BeeWatch.  If not, see <http://www.gnu.org/licenses/>.
#

import argparse
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
import logging
import logging.config
import logging.handlers
import sys
# import mylibnetwork
import threading
import socket
import traceback
import time
import yaml

import blinker
import curio

import beewatch
# import beewatch
import beewatch.server
# import beewatch.server as beeserver
import digilib.misc


Notify.init("Bee Watch Server")

log = logging.getLogger(__name__+"")

parser = argparse.ArgumentParser(
    # usage="use this to play",
    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=8054,
    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(
    "--log-ip",
    dest="log_ip",
    default=False,
    action="store_false",
    help="WARNING: THIS FLAG ENABLES IP 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()

if args.debug:
    digilib.misc.load_files("config/logging.yaml",logging.config.dictConfig)

if args.af_family == "AF_UNIX":
    port = None
elif args.af_family == "AF_INET":
    port = args.port

config_files = [
    "config/controllers.yaml",
    "config/commands.yaml",
]

digilib.misc.load_files(config_files,beewatch.Configure)

bee_server = beewatch.server.BeeWatchServer(
    host=args.host,
    port=args.port,
    af_family=args.af_family,
    log_ip=args.log_ip,
)

sig_exit = blinker.signal("global-exit")

try:
    bee_server.start()
    print(bee_server.run)
except Exception as e:
    log.warn("an error occured, aborting")
    log.error(e, exc_info=True)
except KeyboardInterrupt:
    print("\r    ", end="\r")
    logging.warn("KeyboardInterrupt! aborting!")
finally:
    bee_server.shutdown()
    sig_exit.send()
    log.info("have a good time :)")
    pass


sys.exit()





































#