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

    def doCheck(self):
        databaseListSql = "select datname from pg_catalog.pg_database where datname != 'template0';"
        sqlcmd = "show server_encoding;"
        dbList = SharedFuncs.runSqlCmd(databaseListSql, self.user, "", self.port, self.tmpPath, "postgres",
                                       self.mpprcFile).split('\n')
        sqlPath = os.path.realpath(os.path.join(os.path.split(os.path.realpath(__file__))[0],
                                                "../../lib/checkblacklist/"))
        sqlFileName = os.path.join(sqlPath, "GetTable_unsupportHDFSForeignTable.sql")
        self.result.val = ""
        self.result.raw = ""
        failedFlag = False

        for dbname in dbList:
            raw_list = []
            result_list = []
            # Check database encoding
            output = SharedFuncs.runSqlCmd(sqlcmd, self.user, "", self.port, self.tmpPath, dbname, self.mpprcFile)
            result_list.append("\ndatabase[%s]\nserver_encoding: %s\n" % (dbname, output))
            raw_list.append("\ndatabase[%s]: %s\n" % (dbname, output))
            if output.strip().upper() not in ['LATIN-1', 'ISO-8859-1', 'SQL_ASCII']:
                # Check HDFS foreign table
                cmd = "gsql -m -d %s -p %s -f %s" % (dbname, self.port, sqlFileName)
                output = SharedFuncs.runShellCmd(cmd, self.user, self.mpprcFile)
                raw_list.append("\n%s" % output)
                self.result.raw = "".join(raw_list)
                if output.find("0 rows") < 0:
                    tableList = output.split('\n')[:-2]
                    result_list.append("HDFS foreign table:\n")
                    result_list.append("\n".join(tableList))
                    result_str = "".join(result_list)
                    self.result.val += result_str
                    failedFlag = True

        if failedFlag:
            self.result.rst = ResultStatus.NG
        else:
            self.result.rst = ResultStatus.OK
