#!/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.
For those PV's that are truly disconnected, if the PV's have not connected for more than a certain time, there is an option to pause them.
'''
from __future__ import print_function

import os
import sys
import argparse
import time
import urllib
import json
import datetime
import time
import determineFacility
import emailHandler
import multiplePVCheck
import six.moves.urllib.request as urllib2

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

def pausePVs(bplURL, pvNames):
    '''Pause the PV's in the pvNames list using bulk pause''' 
    url = bplURL + '/pauseArchivingPV'
    req = urllib2.Request(url, json.dumps(pvNames), {'Content-Type': 'application/json'})
    response = urllib2.urlopen(req)
    the_page = response.read()
    pauseStatus = json.loads(the_page)
    return pauseStatus


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")
    parser.add_argument('-p', "--pauseIfNotConnectedFor", help="Pause the PV's if the archiver has not been able to connect to the PV for this many seconds")
    args = parser.parse_args()
    
    skipSendingEmail = args.skipSendingEmail
    url = determineFacility.determineMgmtURLFromArgs(args)
    pauseIfNotConnectedInSecs = -1
    pauseDisconnectedPVs = False
    if args.pauseIfNotConnectedFor is not None:
        pauseIfNotConnectedInSecs = int(args.pauseIfNotConnectedFor)
        pauseDisconnectedPVs = True


    currentlyDisconnectedPVs = getCurrentlyDisconnectedPVs(url)

    timeout = 10
    if 'timeout' in args:
        timeout = int(args.timeout)
        
    if len(currentlyDisconnectedPVs) > 0:
        pvs = []
        pv2disconnecttime = {}
        for currentlyDisconnectedPV in currentlyDisconnectedPVs:
            pvName = currentlyDisconnectedPV['pvName']
            pvs.append(pvName)
            pv2disconnecttime[pvName] = int(currentlyDisconnectedPV['noConnectionAsOfEpochSecs'])
        connectedPVs = multiplePVCheck.checkMultiplePVs(pvs, timeout)
        pvsToSendEmailAbout = []
        pvsToPause = []
        currentEpochSeconds = int(time.time())
        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)
            else:
                if pauseDisconnectedPVs and ((currentEpochSeconds - pv2disconnecttime[pvName]) > pauseIfNotConnectedInSecs):
                    pvsToPause.append(pvName)
                    
        if len(pvsToSendEmailAbout) > 0:
            if(skipSendingEmail):
                print("\n".join(pvsToSendEmailAbout))
            else:
                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. If this problem persists for more than a couple of hours, please contact Murali Shankar or Patrick Pascual. In case these folks are not available, you can consider pausing and resuming these PVs. If this does not work, 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 as a last resort.", pvsToSendEmailAbout)

        if pauseDisconnectedPVs and len(pvsToPause) > 0:
            pausePVs(url, pvsToPause)
            if(skipSendingEmail):
                print("Pausing {1} disconnected PVs in {0}".format(url, len(pvsToPause)))
                print("\n".join(pvsToPause))
            else:
                emailSubject = "Paused {1} disconnected live PVs in {0}\n".format(url, len(pvsToPause))
                emailHandler.sendEmail(emailSubject, "Paused these PV's as they have not connected in more than {0} seconds.",format(pauseIfNotConnectedInSecs), pvsToPause)

