# @package      hubzero-submit-common
# @file         RemoteProbeMonitor.py
# @copyright    Copyright (c) 2012-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2012-2020 The Regents of the University of California.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of The Regents of the University of California.
#
import time
import traceback
import logging

from hubzero.submit.LogMessage        import getLogIDMessage as getLogMessage
from hubzero.submit.MessageConnection import MessageConnection

class RemoteProbeMonitor(MessageConnection):
   def __init__(self,
                listenURI,
                ignoreProbeSites=[]):
      MessageConnection.__init__(self,listenURI)

      self.logger = logging.getLogger(__name__)

      self.results = {}
      self.ignoreProbeSites = []
      for site in ignoreProbeSites:
         self.ignoreProbeSites.append(site)


   def isSiteAvailable(self,
                       queueAtSite):
      siteName = queueAtSite
      if   siteName in self.results:
         siteAvailable = self.results[siteName]
      elif siteName in self.ignoreProbeSites:
         siteAvailable = True
         self.results[siteName] = siteAvailable
      else:
         timeEvaluated,status,waitRank = self.queryProbeSiteStatus(siteName)
         siteAvailable = (status == "PASSED")
         self.results[siteName] = siteAvailable

      return(siteAvailable)


   def queryProbeSiteStatus(self,
                            siteName):
      timeEvaluated = 0
      status        = ""
      waitRank      = 0

      queryMessage = {'messageType':'queryProbe',
                      'probeDesignator':siteName}
      nTry,response = self.requestJsonExchange(queryMessage)

      if nTry > 1:
         self.logger.log(logging.WARNING,getLogMessage("confirmation: queryProbe(%d):%s" % (nTry,response['messageType'])))

      if response:
         timeEvaluated = response['timeEvaluated']
         status        = response['status']
         waitRank      = response['waitRank']

      return(timeEvaluated,status,waitRank)


   def postProbeSiteUpdate(self,
                           siteName,
                           timeEvaluated,
                           status,
                           waitTime):
      queryMessage = {'messageType':'updateProbe',
                      'probeDesignator':siteName,
                      'timeEvaluated':timeEvaluated,
                      'status':status,
                      'waitTime':waitTime}
      nTry,response = self.requestJsonExchange(queryMessage)

      if nTry > 1:
         self.logger.log(logging.WARNING,getLogMessage("confirmation: updateProbe(%d):%s" % (nTry,response['messageType'])))


   def postProbeSiteUpdateSuspension(self,
                                     siteName,
                                     suspendStartTime,
                                     suspendEndTime):
      queryMessage = {'messageType':'updateSuspension',
                      'probeDesignator':siteName,
                      'suspendStartTime':suspendStartTime,
                      'suspendEndTime':suspendEndTime}
      nTry,response = self.requestJsonExchange(queryMessage)

      if nTry > 1:
         self.logger.log(logging.WARNING,getLogMessage("confirmation: updateSuspension(%d):%s" % (nTry,response['messageType'])))


   def deleteProbeSite(self,
                       siteName):
      siteDeleted = False

      queryMessage = {'messageType':'deleteProbe',
                      'probeDesignator':siteName}
      nTry,response = self.requestJsonExchange(queryMessage)

      if nTry > 1:
         self.logger.log(logging.WARNING,getLogMessage("confirmation: deleteProbe(%d):%s" % (nTry,response['messageType'])))

      siteDeleted = response['success']

      return(siteDeleted)


   def reportProbeSiteStatus(self):
      report = {}

      queryMessage = {'messageType':'reportProbe',
                      'probeDesignator':"*"}
      nTry,response = self.requestJsonExchange(queryMessage)

      if nTry > 1:
         self.logger.log(logging.WARNING,getLogMessage("confirmation: reportProbe(%d):%s" % (nTry,response['messageType'])))

      report = response['statusReport']

      return(report)


