#!/usr/bin/env python3
#
# (c) 2017 Fetal-Neonatal Neuroimaging & Developmental Science Center
#                   Boston Children's Hospital
#
#              http://childrenshospital.org/FNNDSC/
#                        dev@babyMRI.org
#

import sys, os
sys.path.insert(1, os.path.join(os.path.dirname(__file__), '..'))

import  socket
from    argparse            import RawTextHelpFormatter
from    argparse            import ArgumentParser
#from    distutils.sysconfig import get_python_lib

import  pudb

import  pfdcm
# The following convolutions are necessary to accommodate both
# development and deployed instances of the 'pfcon.py' module
# and related dependencies.
# sys.path.insert(1, os.path.join(os.path.dirname(__file__), '../pfdcm'))
# try:
#     import  pfdcm
# except:
#     sys.path.insert(1, os.path.join(get_python_lib(True, True), 'site-packages'))
#     sys.path.insert(1, os.path.join(get_python_lib(True, True), 'site-packages/pfcon'))
#     import  pfcon
from    pfdcm._colors   import Colors

str_defIP = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
str_version = "1.1.7.dev0"
str_desc = Colors.CYAN + """

         __      _                  
        / _|    | |                 
 _ __  | |_   __| |  ___  _ __ ___  
| '_ \ |  _| / _` | / __|| '_ ` _ \\ 
| |_) || |  | (_| || (__ | | | | | |
| .__/ |_|   \__,_| \___||_| |_| |_|
| |                                 
|_|                                 


                            Path-File-DICOM

           A service for DICOM handling -- part of the pf* family.

                              -- version """ + \
             Colors.YELLOW + str_version + Colors.CYAN + """ --

    'pfdcm' is a module class and stand-alone app that provides a simple API 
    (both programmatically and CLI-driven) to coordinate data transfers and 
    management of DICOM data from a remote DICOM server.

    It also provides various DICOM related management services:

        - PACS Q/R
        - PACS PUSH
        - Anonymization
    
""" + \
        Colors.BLINK_RED +  """
        
            +-----------------------------------------------------------+
            | NOTE THAT THIS SERVER DOES NOT CURRENTLY AUTHENTICATE AND |
            | WILL HONOR *ALL* DATA PUSH AND PROCESS CONTROL REQUESTS!  |
            +-----------------------------------------------------------+
              
""" + Colors.NO_COLOUR

parser  = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter)

parser.add_argument(
    '--ip',
    action  = 'store',
    dest    = 'ip',
    default = str_defIP,
    help    = 'IP to connect.'
)
parser.add_argument(
    '--port',
    action  = 'store',
    dest    = 'port',
    default = '5015',
    help    = 'Port to use.'
)
parser.add_argument(
    '--version',
    help    = 'if specified, print version number',
    dest    = 'b_version',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--forever',
    help    = 'if specified, serve forever, otherwise terminate after single service.',
    dest    = 'b_forever',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--test',
    help    = 'if specified, perform internal tests',
    dest    = 'b_test',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--httpResponse',
    help    = 'if specified, return HTTP responses',
    dest    = 'b_httpResponse',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--startlistener',
    help    = 'if specified, define and start an xinetd controlled listener service',
    dest    = 'b_xinetd',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--setPACS',
    action  = 'store',
    dest    = 'setPACS',
    default = '',
    help    = 'Configure the settings for a PACS.'
)

args            = parser.parse_args()
args.port       = int(args.port)

if args.b_version:
    print("Version: %s" % str_version)
    sys.exit(1)

# pudb.set_trace()
server          = pfdcm.ThreadedHTTPServer((args.ip, args.port), pfdcm.StoreHandler)
server.setup(args = vars(args), desc = str_desc, ver = str_version)

if args.b_xinetd:
    handler     = pfdcm.StoreHandler(xinetd = True)

if args.b_test:
    handler     = pfdcm.StoreHandler(test = True)
    handler.do_POST(
        d_msg = {
            "action": "hello",
            "meta": {
                "askAbout":     "sysinfo",
                "echoBack":     "Hi there!"
                }
            }
    )
    sys.exit(0)

if args.b_forever and not args.b_test:
    server.serve_forever()
else:
    server.handle_request()
