#!/usr/bin/env python

#  Sep-25-2014  Murali Shankar  Added mode/sampling period for Shanta
#  Feb-06-2014  Murali Shankar  Initial version



import os
import sys
import urllib
import urllib2
import json
import argparse

facilities = { 
    'LCLS' : 'http://lcls-archapp.slac.stanford.edu/mgmt/bpl/',
    'FACET' : 'http://facet-archapp.slac.stanford.edu/mgmt/bpl/',
    'TestFac' : 'http://testfac-archapp.slac.stanford.edu/mgmt/bpl/'
}


def getAllPVs(bplURL, matchingPVs):
    '''Gets all the PVS in the appliance. Note; this can return millions of PVs'''
    pvArg = '*'
    if matchingPVs:
        first = True
        for matchingPV in matchingPVs:
            if first:
                first = False
                pvArg = pvArg + urllib.quote(matchingPV)
            else:
                pvArg = pvArg + ',' + urllib.quote(matchingPV)
                
    url = bplURL + '/getAllPVs?pv=' + pvArg
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    the_page = response.read()
    allPVs = json.loads(the_page)
    return allPVs

def getDetailedPVs(bplURL, matchingPVs):
    '''Gets all the PVS in the appliance. Note; this can return millions of PVs'''
    pvArg = '*'
    if matchingPVs:
        first = True
        for matchingPV in matchingPVs:
            if first:
                first = False
                pvArg = pvArg + urllib.quote(matchingPV)
            else:
                pvArg = pvArg + ',' + urllib.quote(matchingPV)
                
    url = bplURL + '/getPVStatus?pv=' + pvArg
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    the_page = response.read()
    allPVs = json.loads(the_page)
    return allPVs

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="A small utility to list the PVs that are currently being archived in a facility. You can specify one or more GLOB patterns, for example, VPIO:LI20:*:VRAW")
    parser.add_argument("-u", "--url", help="This is the URL to the mgmt bpl interface of the appliance cluster. For example, http://arch.slac.stanford.edu/mgmt/bpl")
    parser.add_argument("-f", "--facility", help="Specify the facility. This can be one of " + ",".join(facilities.keys()))
    parser.add_argument("-l", "--details", action='store_true', help="List the mode and sampling period as well")
    parser.add_argument("pvs", help="One or more PV patterns; for example, VPIO:LI20:*:VRAW", nargs='*')
    args = parser.parse_args()
    if not args.url and not args.facility:
        print "You must specify either the facility or a URL to an appliance. Use -h to determine options for this command."
        sys.exit(1)
    # First get the url from the facility if present
    url = None
    if args.facility:
        if args.facility not in facilities:
            print "Facility must be one of " + ",".join(facilities.keys())
            sys.exit(1)
        else:
           url = facilities[args.facility]
    else:
        if args.url:
            url = args.url
        else:
            print "You must specify either the facility or a URL to an appliance. Use -h to determine options for this command." 
            sys.exit(1)

    if args.details:
        pvStatuses = getDetailedPVs(url,args.pvs)
        print "{0}\t{1}\t{2}".format('Name', 'Mode', 'Period')
        for pvStatus in sorted(pvStatuses, key=lambda k: k['pvName']):
            print "{0}\t{1}\t{2}".format(pvStatus['pvName'], 'MONITOR' if pvStatus['isMonitored'] == 'true' else 'SCAN', pvStatus['samplingPeriod'])
    else:
        allPVs = getAllPVs(url,args.pvs)
        for pv in sorted(allPVs):
            print pv

