#!/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 CheckHashIndex(BaseItem):
    def __init__(self):
        super(CheckHashIndex, self).__init__(self.__class__.__name__)

    def doCheck(self):
        databaseListSql = "select datname from pg_catalog.pg_database where datname != 'template0';"
        sqlcmd = """
SELECT
n.nspname AS schemaname,
c.relname AS tablename,
i.relname AS indexname,
o.amname  AS indexmethod,
pg_catalog.pg_get_indexdef(i.oid) AS indexdef
FROM pg_catalog.pg_index x
JOIN pg_catalog.pg_class c ON c.oid = x.indrelid
JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid
JOIN pg_catalog.pg_am    o ON o.oid = i.relam
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'::"char"
AND i.relkind = 'i'::"char"
AND o.amname not in ('btree','gin','psort','cbtree');
"""
        output = SharedFuncs.runSqlCmd(databaseListSql, self.user, "", self.port, self.tmpPath, "postgres",
                                       self.mpprcFile)
        dbList = output.split("\n")
        resultStr = ""
        for databaseName in dbList:
            output = SharedFuncs.runSqlCmd(sqlcmd, self.user, "", self.port, self.tmpPath, databaseName,
                                           self.mpprcFile, True)
            if (output):
                self.result.raw += "%s: %s" % (databaseName, output)
                tableList = output.split('\n')
                resultStr += "database[%s]: %s\n" % (databaseName, ",".join(tableList))

        if (resultStr):
            self.result.rst = ResultStatus.NG
            self.result.val = resultStr
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "There is no hash index in all databases."
