import pprint
import time
import requests

from checks import AgentCheck

class AlfSolrCheck(AgentCheck):
    timeMap = {'Second':1,'Minute':60,'Hour':3600,'Day':86400,'Month':2592000,'Year':31536000}
    SUMMARY = 'Summary'
    ALFRESCO = 'alfresco'
    ARCHIVE = 'archive'
    ATITR = 'Approx transaction indexing time remaining'
    ATR = 'Approx transactions remaining'
    TX_LAG = 'TX Lag'
    SOLR4= 'solr4'


    def check(self, instance):
        if 'host' not in instance:
            self.log.error("Skipping instance, no url found.")
            return
        if 'port' not in instance:
            self.log.error("Skipping instance, no port found.")
            return

        port = str(instance['port'])
        url = 'http://'+instance['host']+':'+port+'/solr4/admin/cores?action=SUMMARY&wt=json'

        default_timeout = self.init_config.get('default_timeout', 5)
        timeout = float(instance.get('timeout', default_timeout))

        start_time = time.time()
        try:
            r = requests.get(url, timeout=timeout)
            end_time = time.time()
            json = r.json()
        except requests.exceptions.Timeout as e:
          # If there's a timeout
          self.timeout_event(url, timeout)
          return
        except requests.exceptions.ConnectionError as e:
          self.connectionerror_event(url)
          return
        except ValueError as e:
          self.log.error("Invalid JSON returned")
          self.jsonerror_event(url)
          return

        if r.status_code != 200:
          self.status_code_event(url, r)
          return

        if not json:
          self.jsonerror_event(url)
          return

        try:
          summary_json = json[self.SUMMARY]
          alfresco = summary_json[self.ALFRESCO]
          archive = summary_json[self.ARCHIVE]
        except KeyError as e:
          self.log.error("Invalid JSON returned")
          self.jsonerror_event(url)
          return

        alfIndexingRemaining = alfresco[self.ATITR]
        archiveIndexingRemaining = archive[self.ATITR]

        alfApproxTnxRemaining = alfresco[self.ATR]
        archApproxTnxRemaining = archive[self.ATR]

        alfTXLag = alfresco[self.TX_LAG]
        archTXLag = archive[self.TX_LAG]

        alfIndexingRemainingNum = self.getSecFromTransactionString(alfIndexingRemaining)
        archiveIndexingRemainingNum = self.getSecFromTransactionString(archiveIndexingRemaining)
        alfTXLagNum = self.getSecFromLagString(alfTXLag)
        archTXLagNum = self.getSecFromLagString(archTXLag)

        self.gauge('solr4.tracker.alfresco.approx.txns.remaining', alfApproxTnxRemaining, tags=[self.SOLR4])
        self.gauge('solr4.tracker.archive.approx.txns.remaining', archApproxTnxRemaining, tags=[self.SOLR4])
        self.gauge('solr4.tracker.alfresco.approx.indexing.time.remaining', alfIndexingRemainingNum, tags=[self.SOLR4])
        self.gauge('solr4.tracker.archive.approx.indexing.time.remaining', archiveIndexingRemainingNum, tags=[self.SOLR4])
        self.gauge('solr4.tracker.alfresco.lag', alfTXLagNum, tags=[self.SOLR4])
        self.gauge('solr4.tracker.archive.lag', archTXLagNum, tags=[self.SOLR4])

    def connectionerror_event(self, url):
            self.event({
                'timestamp': int(time.time()),
                'event_type': self.SOLR4,
                'msg_title': 'Solr Connection error',
                'msg_text': '%s SOLR Connection Error' % (url),
                'alert_type': 'error'
            })

    def jsonerror_event(self, url):
            self.event({
                'timestamp': int(time.time()),
                'event_type': self.SOLR4,
                'msg_title': 'Solr Invalid JSON error',
                'msg_text': '%s SOLR Invalid JSON Error' % (url),
                'alert_type': 'error'
            })

    def timeout_event(self, url, timeout):
            self.event({
                'timestamp': int(time.time()),
                'event_type': self.SOLR4,
                'msg_title': 'URL timeout',
                'msg_text': '%s timed out after %s seconds.' % (url, timeout),
                'alert_type': 'warning'
            })

    def status_code_event(self, url, r):
            self.event({
                'timestamp': int(time.time()),
                'event_type': self.SOLR4,
                'msg_title': 'Invalid reponse code for %s' % url,
                'msg_text': '%s returned a status of %s' % (url, r.status_code)
            })

    def getSecFromTransactionString(self,value):
        split = value.split()
        if len(value)<2 or len(split)<2:
            return 0
        try:
            num = int(float(split[0]))
            time = split[1]
            if time.endswith('s'):
                time = time[:-1]
            return num*self.timeMap[time]
        except ValueError as e:
            self.log.error(e)
            return 0


    def getSecFromLagString(self,value):
        split = value.split()
        if len(value)<2 or len(split)<2:
            return 0
        try:
            res = int(float(split[0]))
            return res
        except ValueError as e:
            self.log.error(e)
            return 0
