#!/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 e:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(e))


class CheckActQryCount(BaseItem):
    def __init__(self):
        super(CheckActQryCount, self).__init__(self.__class__.__name__)

    def doCheck(self):
        sql = "show max_active_statements;"
        self.result.raw = sql
        max_active_statements = SharedFuncs.runSqlCmd(sql, self.user, "", self.port, self.tmpPath, "postgres",
                                                      self.mpprcFile)
        self.result.val = "max_active_statements: %s" % max_active_statements
        if (int(max_active_statements) == -1):
            self.result.rst = ResultStatus.OK
            return
        sqlcmd = "SELECT count(query)-1 FROM pg_catalog.pg_stat_activity WHERE state != 'idle';"
        self.result.raw += sqlcmd
        output = SharedFuncs.runSqlCmd(sqlcmd, self.user, "", self.port, self.tmpPath, "postgres", self.mpprcFile)
        self.result.val += "\nActive connections: %s" % output
        if (int(output) > int(max_active_statements)):
            self.result.rst = ResultStatus.WARNING
        else:
            self.result.rst = ResultStatus.OK
