#!/usr/bin/env python
'''
Checks to see if we can connect to the PV's that are currently disconnected.
This is useful to get around any CA/Geteway bugs where the archiver does not connect to PV's while CA can.
Run this within the facility VLAN bypassing any gateways, name servers etc.
'''

import os
import sys
import argparse
import time
import urllib
import urllib2
import json
import datetime
import time
import determineFacility
import emailHandler
import multiplePVCheck

def getCurrentlyDisconnectedPVs(bplURL):
    '''Get a list of PVs that are currently disconnected'''
    url = bplURL + '/getCurrentlyDisconnectedPVs'
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    the_page = response.read()
    currentlyDisconnectedPVs = json.loads(the_page)
    return currentlyDisconnectedPVs


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    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('-t', "--timeout", default="5", help="Specify the timeout to wait for all the PV's to connect")
    parser.add_argument("--skipSendingEmail", action='store_true', help="Skip sending an email and print the results")
    args = parser.parse_args()
    
    skipSendingEmail = args.skipSendingEmail
    url = determineFacility.determineMgmtURLFromArgs(args)

    currentlyDisconnectedPVs = getCurrentlyDisconnectedPVs(url)
    if(skipSendingEmail):
        print currentlyDisconnectedPVs
        sys.exit(0)

    timeout = 10
    if 'timeout' in args:
        timeout = int(args.timeout)
        
    if len(currentlyDisconnectedPVs) > 0:
        pvs = []
        for currentlyDisconnectedPV in currentlyDisconnectedPVs:
            pvName = currentlyDisconnectedPV['pvName']
            pvs.append(pvName)
        connectedPVs = multiplePVCheck.checkMultiplePVs(pvs, timeout)
        pvsToSendEmailAbout = []
        for pvName in pvs:
            if pvName in connectedPVs:
                # We now have a PV that the archiver cannot connect to but we can outside in the facility's VLAN 
                pvsToSendEmailAbout.append(pvName)
        if len(pvsToSendEmailAbout) > 0:
            emailSubject = "{1} disconnected live PVs in {0}\n".format(url, len(pvsToSendEmailAbout))
            emailHandler.sendEmail(emailSubject, "We can connect to these PVs in the facility VLAN but not from the archiver. Please contact Murali Shankar or Sashi Divekar. In case these folks are not available, you can consider restarting the appliances for this facility as outlined in the document http://www.slac.stanford.edu/grp/cd/soft/unix/slaconly/archiver_appliance_operation.html", pvsToSendEmailAbout)


