#!/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))


def validateOutput(output):
    if len(output.splitlines()) == 1:
        return True, ""
    else:
        return False, "\n".join(output.splitlines()[1:])


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

    def doCheck(self):
        errors = []
        sqlcmd = "select * from pg_catalog.pg_resource_pool;" \
                 "select * from pg_catalog.pg_workload_group;" \
                 "select * from pg_catalog.pg_app_workloadgroup_mapping"
        self.result.raw = sqlcmd
        for sql in sqlcmd.split(';'):
            output = SharedFuncs.runSqlCmd(sql, self.user, "", self.port, self.tmpPath, "postgres", self.mpprcFile)
            self.result.raw = "%s\n%s" % (self.result.raw, output)
            status, error = validateOutput(output)
            if not status:
                errors.append(error)
        if len(errors) > 0:
            self.result.rst = ResultStatus.WARNING
            self.result.val = "\n".join(errors)
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "There is no new user cgroup."
