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


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

    def doCheck(self):
        elkEnv = os.getenv("ELK_SYSTEM_TABLESPACE")
        if (not elkEnv):
            self.result.rst = ResultStatus.OK
            self.result.val = "There is no elk databases."
            return

        databaseListSql = "select datname from pg_database where datname != 'template0';"
        sqlcmd = """
SELECT
    n.nspname as namespace,
    c.relname as tablename,
    reloptions
FROM pg_catalog.pg_class c
INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
INNER JOIN pg_catalog.pg_settings s on (s.name = 'enable_hadoop_env'  and s.setting = 'on')
WHERE c.oid > 16384
AND relkind = 'r' and relpersistence not in ('u', 't')
AND (reloptions::text NOT LIKE '%orientation=orc%')
AND reloptions::text NOT LIKE '%internal_mask%'
AND nspname <> 'cstore'
ORDER BY 1,2,3;
"""
        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 non-HDFS table in all databases."
