#!/usr/bin/env python
###################################################################################################
#   COMMAND LINE INTERFACE
###################################################################################################
#
# This file gives the Command Line Interface for FofbTool
#
###################################################################################################

if __name__ == '__main__':
    import logging
    import argparse
    import os
    import sys

    # Safer import: add the parent dir in path
    sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
    import FofbTool.Utils
    import FofbTool.Operation

    # Get the module logger
    logger = logging.getLogger("FofbTool")

    # Add a Stream handler to the module logger
    sh=logging.StreamHandler()
    sh.setLevel(logging.DEBUG)
    sh.setFormatter(logging.Formatter("{levelname:8}: {message}", style='{'))
    logger.addHandler(sh)

    # Add a file handler
    logpath="/home/data/DG/FOFB/FofbTool.log"
    try:
        fh=logging.FileHandler(logpath)
    except FileNotFoundError:
        logger.warning("Not logging to file, could not open location {}".format(logpath))
    else:
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(logging.Formatter("{asctime} {levelname:8}: {message}", style='{'))
        logger.addHandler(fh)

    parser = argparse.ArgumentParser("FofbTool", description="version {}".format(FofbTool.__version__))
    parser.add_argument("--log", default="info",
            help="Log level (error, warning, info, debug)")

    parser.add_argument("--force", action="store_true",
            help="Force operation even if FOFB is running.")

    parser.add_argument("--fileconfig", type=str,
            help="Path to config file to apply.")

    parser.add_argument("--DS-init-opcua", action="store_true",
            help="Run init on opcua devices.")
    parser.add_argument("--DS-init-watcher", action="store_true",
            help="Run init on the Fofb-Watcher device, and then the Fofb-Command.")
    parser.add_argument("--DS-conf", action="store_true",
            help="Applying attribute configuration on Tango Device Servers. This is required after restart of devices.")

    parser.add_argument("--stop", action="store_true",
            help="Stop command for the CCN and ComBPM applications blocks.")
    parser.add_argument("--stop-combpm", action="store_true",
            help="Stop command for the ComBPM applications blocks.")
    parser.add_argument("--stop-ccn", action="store_true",
            help="Stop command for the ComBPM applications blocks.")
    parser.add_argument("--stop-comlbp", action="store_true",
            help="Stop command for the ComLBP applications blocks.")

    parser.add_argument("--dump-configuration", type=argparse.FileType('w'),
            help="Dump the current configuration in a file at the giver path.")

    parser.add_argument("--configure", choices=["combpm", "ccn", "comcorr", "corr", "all"],
            nargs='?', const='all',
            help="Configuration commands for the Fofb applications blocs."+
            " 'all' is for all com and corrector. Default is 'all'")

    parser.add_argument("--align-fa", type=str, metavar="cellnode-cXX",
            help="Start alignement process for electron and brillance plus FA sequence. The designation of the cellnode must be set as argument.")

    parser.add_argument("--nolbp", action="store_true",
            help="Do not start comlbp module when doing start.")

    parser.add_argument("--start", action="store_true",
            help="Start command for the CCN and ComBPM applications blocks.")
    parser.add_argument("--start-combpm", action="store_true",
            help="Start command for the ComBPM applications blocks.")
    parser.add_argument("--start-comlbp", action="store_true",
            help="Start command for the ComLBP applications blocks.")
    parser.add_argument("--start-ccn", action="store_true",
            help="Start command for the ComBPM applications blocks.")

    parser.add_argument("--sync", action="store_true",
            help="Start synchronization sequence for Libera Electron and Libera Brillance Plus.")

    args = parser.parse_args()

    # Set log level from args
    logger.setLevel(getattr(logging, args.log.upper()))

    logger.debug(args)
    logger.info("FofbTool version {}".format(FofbTool.__version__))

    if not args.fileconfig is None:
        FofbTool.Utils.loadconfig(args.fileconfig)
    FofbTool.Utils.logdebugconf()

    if not args.dump_configuration is None:
        FofbTool.Utils.config.write(args.dump_configuration)
        args.dump_configuration.close()


    ## Check running
    if not FofbTool.Utils.check_fofbnotrunning(force=args.force):
        logger.warning("FOFB is running, Stopping here")
        exit(1)

    ## Device Server related commands
    if args.DS_init_opcua:
        FofbTool.Utils.init_opcua(force=args.force)

    if args.DS_init_watcher:
        FofbTool.Utils.init_watcher(force=args.force)

    if args.DS_conf:
        FofbTool.Utils.confds_opcua()

    if args.stop or args.stop_combpm:
        FofbTool.Utils.stop_all_combpm(force=args.force)
    if args.stop or args.stop_comlbp:
        FofbTool.Utils.stop_all_comlbp(force=args.force)
    if args.stop or args.stop_ccn:
        FofbTool.Utils.stop_all_ccn(force=args.force)

    if args.configure in ("combpm", "all"):
        FofbTool.Utils.conf_all_combpm(force=args.force)
    if args.configure in ("comcorr", "all"):
        FofbTool.Utils.conf_all_comcorr(force=args.force)
    if args.configure in ("ccn", "all"):
        FofbTool.Utils.conf_all_ccn(force=args.force)
    if args.configure in ("corr", "all"):
        FofbTool.Utils.conf_centralnode_corr()

    if args.sync:
        FofbTool.Utils.sync_all_bpm()

    if (args.start or args.start_comlbp) and not args.nolbp:
        FofbTool.Utils.start_all_comlbp()
    if args.start or args.start_combpm:
        FofbTool.Utils.start_all_combpm()
    if args.start or args.start_ccn:
        FofbTool.Utils.start_all_ccn()

    if not args.align_fa is None:
        FofbTool.Utils.align_all_ccn(args.align_fa, force=args.force)