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

SQL_TABLES = "select b.nspname, a.relname, reloptions" \
             " from pg_catalog.pg_class a, pg_catalog.pg_namespace b where a.relnamespace = b.oid" \
             " and b.nspname !~ '^pg_toast' and a.relkind='r' and a.relpersistence='p';"
SQL_FOR_CUSTOM = "select b.nspname, a.relname, reloptions" \
                 " from pg_catalog.pg_class a, pg_catalog.pg_namespace b where a.relnamespace = b.oid" \
                 " and b.nspname !~ '^pg_toast' and a.relkind='r' and a.relpersistence='p'" \
                 " and b.nspname <> 'pg_catalog' and b.nspname <> 'cstore'" \
                 " and b.nspname <> 'information_schema' and b.nspname <> 'schema_cur_table_col'" \
                 " and b.nspname <> 'schema_cur_table' and b.nspname !~ '^pg_toast';"
SQL_DB = "select datname from pg_catalog.pg_database;"


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

    def doCheck(self):
        flag = SharedFuncs.getFirstCNInstance(self.user, self.mpprcFile, self.tmpPath)
        if flag or self.cluster.isSingleInstCluster():
            try:
                output = SharedFuncs.runSqlCmd(SQL_DB, self.user, "", self.port, self.tmpPath, "postgres",
                                               self.mpprcFile)
                dbList = output.splitlines()
                dbList.remove("template0")
                dbList.remove("template1")
                for db in dbList:
                    coltable = []
                    rowtable = []
                    if db == "postgres":
                        sql = SQL_TABLES
                    else:
                        sql = SQL_FOR_CUSTOM
                    output = SharedFuncs.runSqlCmd(sql, self.user, "", self.port, self.tmpPath, db, self.mpprcFile)
                    tablelist = output.splitlines()
                    sql = ""
                    for tableinfo in tablelist:
                        if len(tableinfo.split("|")) == 3:
                            schema = tableinfo.split("|")[0].strip()
                            tablename = tableinfo.split("|")[1].strip()
                            reloptions = tableinfo.split("|")[2].strip()
                            if "column" in reloptions:
                                coltable.append("%s.%s" % (schema, tablename))
                            else:
                                rowtable.append("%s.%s" % (schema, tablename))
                        else:
                            pass
                    for table in rowtable:
                        sql = "%sselect count(*) from %s;\n" % (sql, table)
                    for table in coltable:
                        sql = "%sexplain analyze select * from %s;\n" % (sql, table)
                    SharedFuncs.runSqlCmd(sql, self.user, "", self.port, self.tmpPath, db, self.mpprcFile)
            except Exception as e:
                self.result.rst = ResultStatus.NG
                self.result.val = "%s" % e.output
                return
            self.result.rst = ResultStatus.OK
            self.result.val = "No data is distributed on the fault disk"
        else:
            self.result.rst = ResultStatus.NA
            self.result.val = "First cn is not in this host"
