#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    import subprocess
    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))

g_value = 0


class CheckMaxDatanode(BaseItem):
    def __init__(self):
        super(CheckMaxDatanode, self).__init__(self.__class__.__name__)
        self.nodeCount = None
        self.dnCount = None

    def preCheck(self):
        # check current node contains cn instances if not raise  exception
        super(CheckMaxDatanode, self).preCheck()
        # check the threshold was set correctly
        if (not self.threshold.__contains__('nodeCount')):
            raise Exception("threshold nodeCount can not be empty")
        if (not self.threshold.__contains__('dnCount')):
            raise Exception("threshold dnCount can not be empty")

        self.nodeCount = self.threshold['nodeCount']
        self.dnCount = self.threshold['dnCount']

    def doCheck(self):
        global g_value
        dataNum = int(self.nodeCount) * int(self.dnCount)
        sqlcmd = "SELECT setting FROM pg_catalog.pg_settings WHERE name='comm_max_datanode';"
        self.result.raw = sqlcmd
        comm_max_datanode = SharedFuncs.runSqlCmd(sqlcmd, self.user, "", self.port, self.tmpPath, "postgres",
                                                  self.mpprcFile)

        if (dataNum > int(comm_max_datanode)):
            if (dataNum < 256):
                g_value = 256
            elif (dataNum < 512):
                g_value = 512
            elif (dataNum < 1024):
                g_value = 1024
            else:
                g_value = 2048
            self.result.rst = ResultStatus.WARNING
            self.result.val = "Invalid value for GUC parameter comm_max_datanode: %s. Expect value: %s" % (
                comm_max_datanode, g_value)
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "dataNum: %s, comm_max_datanode: %s" % (dataNum, comm_max_datanode)

        self.result.raw = sqlcmd

    def doSet(self):
        cmd = " gs_guc set -Z coordinator -N all -I all -c 'comm_max_datanode=%d'; " % g_value
        cmd += " gs_guc set -Z datanode -N all -I all -c 'comm_max_datanode=%d' " % g_value
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status != 0):
            self.result.val += "Falied to set comm_max_datanode.\n Error : %s " % output
        else:
            self.result.val += "Set comm_max_datanode successfully."
