#!/usr/bin/env python3
# -*- coding:utf-8 -*-
try:
    import sys
    import importlib

    importlib.reload(sys)
    import os
    import subprocess
    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))

SQL_PATH = os.path.realpath(os.path.join(os.path.split(os.path.realpath(__file__))[0], "../../lib/checkcreateview/"))
OUTPUT_PATH = os.path.realpath(os.path.join(os.path.split(os.path.realpath(__file__))[0], "../../output/"))
FILE_MODE = 755


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

    def doCheck(self):
        flag = 1
        resultStr = ""
        databaseListSql = "select datname from pg_catalog.pg_database where datname != 'template0';"
        output = SharedFuncs.runSqlCmd(databaseListSql, self.user, "", self.port, self.tmpPath, "postgres",
                                       self.mpprcFile)
        dbList = output.split("\n")
        sqlFileName = os.path.join(SQL_PATH, "check_viewdef.sql")
        cmd = "chmod %s %s" % (FILE_MODE, sqlFileName)
        SharedFuncs.runShellCmd(cmd)
        for databaseName in dbList:
            sqlFile = "%s/viewdef_%s.sql" % (OUTPUT_PATH, databaseName)
            cmd = "gsql -d %s -p %s -q -t -f %s -o %s/viewdef_%s.sql" % (databaseName, self.port, sqlFileName,
                                                                         OUTPUT_PATH, databaseName)
            if os.getuid() == 0:
                cmd = "su - %s -c \"source %s;%s\"" % (self.user, self.mpprcFile, cmd)
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0:
                resultStr += "execute %s error. Error:%s\n" % (cmd, output)
                flag = 0
                continue
            cmd = "gsql -d %s -p %s -f %s -o %s/viewdef_%s.out " % (databaseName, self.port, sqlFile, OUTPUT_PATH,
                                                                    databaseName)
            if os.getuid() == 0:
                cmd = "su - %s -c \"source %s;%s\"" % (self.user, self.mpprcFile, cmd)
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0:
                resultStr += "execute %s error. Error:%s\n" % (cmd, output)
                flag = 0
                continue
            else:
                flag, resultStr = self.fixed_error_sql(output, sqlFile, databaseName, flag)
        if flag == 0:
            self.result.rst = ResultStatus.NG
            self.result.val = resultStr
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = " No view needs to be fixed."

    def fixed_error_sql(self, output, sqlFile, databaseName, flag):
        resultStr = ""
        for line in output.split("\n"):
            line = line.split(":")
            for word in line:
                if "ERROR" == word.strip():
                    flag = 0
                    errorNum = line[line.index(' ERROR') - 1]
                    with open(os.path.realpath(sqlFile), "r") as fp:
                        sqlLines = fp.readlines()
                    view = sqlLines[int(errorNum) - 1].split()[-1].strip(';')
                    viewList = view.strip('\"').split('.')
                    resultStr = "view %s needs to be fixed" % sqlLines[int(errorNum) - 1].split()[-1].strip(';')
                    cmd = "gs_dump %s -p %s -t '\"%s\"'.'\"%s\"' -f '%s/%s.sql'" \
                          % (databaseName, self.port, viewList[0], viewList[1], OUTPUT_PATH, view.strip('\"'))
                    if os.getuid() == 0:
                        cmd = "su - %s -c \"source %s;%s\"" % (self.user, self.mpprcFile, cmd)
                    (status, output) = subprocess.getstatusoutput(cmd)
                    if status != 0:
                        self.result.val += "execute %s error\n" % cmd
                else:
                    continue
        return flag, resultStr
