#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class CheckPoolerNum(BaseItem):
    def __init__(self):
        super(CheckPoolerNum, self).__init__(self.__class__.__name__)
        self.Threshold_NG = None
        self.Threshold_Warning = None

    def preCheck(self):
        super(CheckPoolerNum, self).preCheck()
        if (not (self.threshold.__contains__('Threshold_NG') and self.threshold.__contains__('Threshold_Warning'))):
            raise Exception("The threshold Threshold_NG and Threshold_Warning can not be empty.")
        if (not self.threshold['Threshold_NG'].isdigit() or not self.threshold['Threshold_Warning'].isdigit()):
            raise Exception("The threshold Threshold_NG and Threshold_Warning must be integer.")
        self.Threshold_NG = int(self.threshold['Threshold_NG'])
        self.Threshold_Warning = int(self.threshold['Threshold_Warning'])

    def doCheck(self):
        sqlcmd = "select count(*) from pg_catalog.pg_pooler_status;"
        self.result.raw = sqlcmd
        output = SharedFuncs.runSqlCmd(sqlcmd, self.user, "", self.port, self.tmpPath, "postgres", self.mpprcFile)
        if (int(output.strip()) > self.Threshold_NG):
            self.result.rst = ResultStatus.NG
        elif(int(output.strip()) > self.Threshold_Warning):
            self.result.rst = ResultStatus.WARNING
        else:
            self.result.rst = ResultStatus.OK
        self.result.val = "The number of used poolers is %s" % output
