#!/usr/bin/env python

from dm.daq_web_service.api.experimentDaqApi import ExperimentDaqApi
from dm.common.exceptions.invalidRequest import InvalidRequest
from daqWebServiceSessionCli import DaqWebServiceSessionCli

class StartDaqCli(DaqWebServiceSessionCli):

    HOURS_PER_DAY = 24

    def __init__(self):
        DaqWebServiceSessionCli.__init__(self, validArgCount=self.ANY_NUMBER_OF_POSITIONAL_ARGS)
        self.addOption('', '--experiment', dest='experimentName', help='Experiment name.')
        self.addOption('', '--data-directory', dest='dataDirectory', help='Experiment data directory URL.')
        self.addOption('', '--dest-directory', dest='destDirectory',
	help='Destination directory relative to experiment root path.')
        self.addOption('', '--duration', dest='duration', help='DAQ duration; it must be specified in hours (h) or days (d). Examples: "8h", "14d".')
        self.addOption('', '--upload-data-directory-on-exit', dest='uploadDataDirectoryOnExit', help='Data directory that will be uploaded automatically after DAQ is stopped.')
        self.addOption('', '--upload-dest-directory-on-exit', dest='uploadDestDirectoryOnExit', help='Destination directory relative to experiment root path for automatic upload after DAQ is stopped. Requires upload data directory to be specified.')
        self.addOption('', '--process-hidden', dest='processHidden', action='store_true', default=False, help='Process hidden source files.')
        self.addOption('', '--skip-plugins', dest='skipPlugins', help='Comma-separated list of plugins which should not process files.')

    def checkArgs(self):
        if self.options.experimentName is None:
            raise InvalidRequest('Experiment name must be provided.')
        if self.options.dataDirectory is None:
            raise InvalidRequest('Experiment data directory must be provided.')

    def updateDaqInfoFromOptions(self, daqInfo):
        if self.options.processHidden:
            daqInfo['processHiddenFiles'] = True
        if self.options.skipPlugins:
            daqInfo['skipPlugins'] = self.options.skipPlugins
        if self.options.duration:
            duration = self.options.duration
            if duration.endswith('h'):
                daqInfo['maxRunTimeInHours'] = int(duration[0:-1])
            elif duration.endswith('d'):
                daqInfo['maxRunTimeInHours'] = int(duration[0:-1])*self.HOURS_PER_DAY
            else:
                raise InvalidRequest('Maximum run time must contain valid unit specifier: "h" for hours or "d" for days.')
        if self.options.destDirectory:
            daqInfo['destDirectory'] = self.options.destDirectory 
        if self.options.uploadDataDirectoryOnExit:
            daqInfo['uploadDataDirectoryOnExit'] = self.options.uploadDataDirectoryOnExit
        if self.options.uploadDestDirectoryOnExit:
            if not self.options.uploadDataDirectoryOnExit:
                raise InvalidRequest('Upload destination directory on exit requires that upload data directory is specified as well.')
            daqInfo['uploadDestDirectoryOnExit'] = self.options.uploadDestDirectoryOnExit

    def runCommand(self):
        self.parseArgs(usage="""
    dm-start-daq --experiment=EXPERIMENTNAME --data-directory=DATADIRECTORY
        [--duration=DURATION]
        [--dest-directory=DESTDIRECTORY]
        [--upload-data-directory-on-exit=UPLOADDATADIRECTORYONEXIT]
        [--upload-dest-directory-on-exit=UPLOADDESTDIRECTORYONEXIT]
        [--process-hidden]
        [key1:value1, key2:value2, ...]

Description:
    Starts DAQ for a given experiment. Specified data directory will be 
    monitored for data files. All provided key/value pairs will be passed to 
    file processing plugins.
        """)
        self.checkArgs()
        api = ExperimentDaqApi(self.getLoginUsername(), self.getLoginPassword(), self.getServiceHost(), self.getServicePort(), self.getServiceProtocol())
        daqInfo = self.splitArgsIntoDict()
        self.updateDaqInfoFromOptions(daqInfo)
        daqInfo = api.startDaq(self.getExperimentName(), self.getDataDirectory(), daqInfo=daqInfo)
        print daqInfo.getDisplayString(self.getDisplayKeys(), self.getDisplayFormat())

#######################################################################
# Run command.
if __name__ == '__main__':
    cli = StartDaqCli()
    cli.run()