#!/usr/bin/env python
'''Takes in a file name with a list of PV's and then determines which of these is archived and which is not'''

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

def getPVStatus(bplURL, fileName):
    '''Send the contents of the file as a POST argument to a getStatus call'''
    url = bplURL + '/getPVStatus'
    with open(fileName, 'r') as f:
        pvlist = f.readlines()
    pvs = [x.strip() for x in pvlist]
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    data = urllib.urlencode({'pv': ",".join(pvs)}) 
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    allPVs = json.loads(the_page)
    return allPVs


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Takes in a file name with a list of PV's and then determines which of these is archived and which is not")
    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("-n", "--notarchived", action="store_true", help="Show only the PVs not being archived")
    parser.add_argument("filename", help="A file containing a list of PV names, one per line")
    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)


    allPVs = getPVStatus(url, args.filename)
    if args.notarchived:
        for pv in allPVs:
            if pv['status'] == 'Not being archived':
                print pv['pvName']
    else:
        for pv in allPVs:
            print pv['pvName'], pv['status']
