#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################################
# Copyright (c): 2012-2017, Huawei Tech. Co., Ltd.
# Description  : Result.py is a utility to store search result from database
#############################################################################
try:
    import os
    import sys
    from ctypes import cdll, c_void_p, c_char_p, c_int, string_at
    from gspylib.common.common.default_value import DefaultValue

    sys.path.append(sys.path[0] + "/../../")
except ImportError as ie:
    sys.exit("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class sqlResult():
    """
    Class for storing search result from database
    """

    def __init__(self, result):
        """
        Constructor
        """
        self.resCount = 0
        self.resSet = []
        self.result = result

    def parseResult(self):
        """
        function : get resCount and resSet from result
        input:NA
        output:NA
        """
        try:
            libpath = os.path.join(DefaultValue.getEnv("GAUSSHOME"), "lib")
            libpq = os.path.join(libpath, "libpq.so.5.5")
            libc = cdll.LoadLibrary(libpq)
            libc.PQntuples.argtypes = [c_void_p]
            libc.PQntuples.restype = c_int
            libc.PQnfields.argtypes = [c_void_p]
            libc.PQnfields.restype = c_int
            libc.PQgetvalue.restype = c_char_p
            ntups = libc.PQntuples(self.result)
            nfields = libc.PQnfields(self.result)
            libc.PQgetvalue.argtypes = [c_void_p, c_int, c_int]
            self.resCount = ntups
            for i in range(ntups):
                tmpString = []
                for j in range(nfields):
                    paramValue = libc.PQgetvalue(self.result, i, j)
                    if (paramValue is not None):
                        tmp_str = string_at(paramValue)
                        try:
                            tmpString.append(tmp_str.decode())
                        except Exception as e:
                            raise Exception("Error: decode error after %s, info: %s" %
                                            (tmp_str.decode(errors='ignore'), str(e)))
                    else:
                        tmpString.append("")
                self.resSet.append(tmpString)
        except Exception as e:
            raise Exception("%s" % str(e))
