#!/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
import determineFacility


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

def mapPVStatus(pvStatus):
    if 'isMonitored' in pvStatus:
        if pvStatus['isMonitored'] == 'true':
            return 'MONITOR'
        else:
            return 'SCAN'
    else:
        return pvStatus['status']

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("-v", "--verbose", action="store_true", help="Enable verbose logging")
    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(determineFacility.facilitiesConfig.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()
    
    verbose = args.verbose 

    url = determineFacility.determineMgmtURLFromArgs(args)
            
    if verbose:
        print "Using management URL ", url
        
    if not url:
        print "Cannot determine the MGMT url for this facility"
        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'], mapPVStatus(pvStatus), pvStatus['samplingPeriod'] if 'samplingPeriod' in pvStatus else 'N/A')
    else:
        allPVs = getAllPVs(url,args.pvs)
        for pv in sorted(allPVs):
            print pv

