#!/usr/bin/env python

import os
import sys
from Detector.UtilsJungfrauCalib import jungfrau_deploy_constants, CALIB_REPO_JUNGFRAU, DIR_LOG_AT_START, uc, gu
import Detector.UtilsLogging as ul
logger = ul.logging.getLogger(__name__)

SCRNAME = sys.argv[0].split('/')[-1]

DESCRIPTION = 'Deployment jungfrau calibration parameters'

USAGE = '\n%s -e <experiment> -d <detector> -r <run-number> [-D] [-L <logging-mode>] [...]' % SCRNAME\
      + '\n\nTEST COMMAND:'\
      + '\nEx.1:  %s -e cxilu9218 -d CxiDs1.0:Jungfrau.0 -r238' % SCRNAME\
      + '\nEx.2:  %s -e cxilu9218 -d CxiDs1.0:Jungfrau.0 -r238 -D -c ./calib' % SCRNAME\
      + '\nEx.3:  %s -e cxic00318 -d CxiDs1.0:Jungfrau.0 -r375 -D -c ./calib -o ./work' % SCRNAME\
      + '\n\nREGULAR COMMAND:'\
      + '\nEx.3:  %s -e cxilu9218 -d CxiDs1.0:Jungfrau.0 -r238 -D' % SCRNAME\
      + '\n\nHelp:  %s -h\n' % SCRNAME

if len(sys.argv)<2:
    print('%s\n%s\n%s' % (40*'_', DESCRIPTION, USAGE))
    sys.exit('MISSING COMMAND LINE PARAMETERS')


def option_parser():
    from optparse import OptionParser

    d_dirrepo = CALIB_REPO_JUNGFRAU # './panels' #CALIB_REPO_JUNGFRAU # '/reg/g/psdm/detector/gains/jungfrau/panels'
    d_exp     = None # 'mfxx32516'
    d_det     = None # 'NoDetector.0:Epix10ka.3'
    d_run     = None # 1021
    d_runrange= None # '0-end'
    d_tstamp  = None # 20180910111049
    d_dsnamex = None # ':smd:dir=/reg/d/psdm/mfx/mfxx32516/scratch/gabriel/pulser/xtc/combined'
    d_dircalib= None # './calib'
    d_paninds = None
    d_deploy  = False
    d_errskip = False
    d_logmode = 'INFO'
    d_dirmode  = 0o2775
    d_filemode = 0o664
    d_group    = 'ps-users'
#    d_high    = 16.40 # 1.
#    d_medium  = 5.466 # 0.33333
#    d_low     = 0.164 # 0.01
#    d_proc    = 'psrg'

    h_exp     = 'experiment name, default = %s' % d_exp
    h_det     = 'detector name, default = %s' % d_det
    h_run     = 'run number for beginning of the validity range, default = %s' % str(d_run)
    h_runrange= 'validity run range for output calibration file, default = %s' % str(d_runrange)
    h_tstamp  = 'non-default time stamp (<YYYYmmddHHMMSS) or run number(<10000) for constants selection in repo. '\
                'By default run time is used, default = %s' % str(d_tstamp)
    h_dsnamex = 'dataset string or xtc file name or extension after exp=<exp>:run=<run> beginning with colon ":", default = %s' % d_dsnamex
    h_dirrepo = 'non-default repository of calibration results, default = %s' % d_dirrepo
    h_dircalib= 'deployment calib directory if different from standard one, default = %s' % d_dircalib
    h_paninds = 'comma-separated (str) panel indexds to generate constants for subset of panels (ex. 2 panel of 8 in the detector), default = %s' % d_paninds
    h_deploy  = 'deploy constants to the calib dir, default = %s' % d_deploy
    h_errskip = 'if possible, skip errors and deploy constants, default = %s' % d_errskip
    h_logmode = 'logging mode, one of %s, default = %s' % (ul.STR_LEVEL_NAMES, d_logmode)
    h_dirmode = 'mode for all mkdir, default = %s' % oct(d_dirmode)
    h_filemode= 'mode for all saved files, default = %s' % oct(d_filemode)
    h_group   = 'group ownership for all files, default = %s' % d_group

#    h_high    = 'default high   gain ADU/keV, default = %s' % str(d_high)
#    h_medium  = 'default medium gain ADU/keV, default = %s' % str(d_medium)
#    h_low     = 'default low    gain ADU/keV, default = %s' % str(d_low)
#    h_proc    = '(str) keyword for processing of "p"-pedestals, "r"-rms, "s"-status, "g" or "c" - gain or charge-injection gain,'\
#              + '  default = %s' % d_proc

    parser = OptionParser(description=DESCRIPTION, usage=USAGE)
    parser.add_option('-e', '--exp',     default=d_exp,     action='store', type='string', help=h_exp)
    parser.add_option('-d', '--det',     default=d_det,     action='store', type='string', help=h_det)
    parser.add_option('-r', '--run',     default=d_run,     action='store', type='string', help=h_run)
    parser.add_option('-R', '--runrange',default=d_runrange,action='store', type='string', help=h_runrange)
    parser.add_option('-t', '--tstamp',  default=d_tstamp,  action='store', type='int',    help=h_tstamp)
    parser.add_option('-x', '--dsnamex', default=d_dsnamex, action='store', type='string', help=h_dsnamex)
    parser.add_option('-o', '--dirrepo', default=d_dirrepo, action='store', type='string', help=h_dirrepo)
    parser.add_option('-c', '--dircalib',default=d_dircalib,action='store', type='string', help=h_dircalib)
    parser.add_option('-I', '--paninds', default=d_paninds, action='store', type='string', help=h_paninds)
    parser.add_option('-D', '--deploy',  default=d_deploy,  action='store_true',           help=h_deploy)
    parser.add_option('-E', '--errskip', default=d_errskip, action='store_true',           help=h_errskip)
    parser.add_option('-L', '--logmode', default=d_logmode, action='store', type='string', help=h_logmode)
    parser.add_option('--dirmode',       default=d_dirmode, action='store', type='int',    help=h_dirmode)
    parser.add_option('--filemode',      default=d_filemode,action='store', type='int',    help=h_filemode)
    parser.add_option('--group',         default=d_group,   action='store', type='string', help=h_group)
#    parser.add_option(      '--high',    default=d_high,    action='store', type='float',  help=h_high)
#    parser.add_option(      '--medium',  default=d_medium,  action='store', type='float',  help=h_medium)
#    parser.add_option(      '--low',     default=d_low,     action='store', type='float',  help=h_low)
#    parser.add_option('-p', '--proc',    default=d_proc,    action='store', type='string', help=h_proc)

    return parser


if __name__ == "__main__":

    parser = option_parser()
    (popts, pargs) = parser.parse_args()

    repoman = uc.RepoManager(dirrepo=popts.dirrepo, dir_log_at_start=DIR_LOG_AT_START,\
                             dirmode=popts.dirmode, filemode=popts.filemode, group=popts.group)
    logname = repoman.logname('%s_%s' % (SCRNAME, gu.get_login()))
    ul.init_logger(loglevel=popts.logmode, logfname=logname, group=popts.group) # fmt='[%(levelname).1s] %(filename)s L%(lineno)04d %(message)s')
    logger.info('log file: %s' % logname)
    repoman.save_record_at_start(SCRNAME, adddict={'logfile':logname})

    from Detector.GlobalUtils import info_command_line_parameters
    logger.info(info_command_line_parameters(parser))
    popts.repoman = repoman
    jungfrau_deploy_constants(pargs, popts)

    os.chmod(logname, popts.filemode)
    uc.cgu.change_file_ownership(logname, user=None, group=popts.group)

    sys.exit(0)

# EOF
