#!/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'''
from __future__ import print_function

import os
import sys
import json
import argparse
import determineFacility
import six.moves.urllib.parse as urllib
import six.moves.urllib.request as urllib2

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)}).encode("utf-8")
    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 {0}".format(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("{0} {1}".format(pv['pvName'], pv['status']))
