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

    sys.path.append(sys.path[0] + "/../../../../")
    from gspylib.common.ErrorCode import ErrorCode
    from gspylib.component.GTM.GTM import GTM
    from gspylib.os.gsplatform import g_Platform
    from gspylib.common.Common import DefaultValue, ClusterInstanceConfig
    from gspylib.os.gsfile import g_file

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


class GTM_OLAP(GTM):
    """
    """

    def __init__(self):
        """
        Constructor
        """
        super(GTM_OLAP, self).__init__()
        self.__gtmParams = []

    def initInstance(self):
        """
        """
        try:
            # Check the instance path
            if self.instInfo.datadir == "":
                raise Exception("Data directory of instance is invalid.")
            if not os.path.exists(self.instInfo.datadir):
                raise Exception(ErrorCode.GAUSS_502["GAUSS_50201"] % ("data directory [%s]" % self.instInfo.datadir))

            # Init the  GTM instance
            image_path = DefaultValue.DWS_IMAGE_PATH
            packageName = "%s/gtm.tar.gz" % image_path
            # old branch that install by image package
            if self.dwsMode and os.path.exists(packageName):
                cmd = g_Platform.getDecompressFilesCmd(packageName, self.instInfo.datadir)
            else:
                cmd = "%s/gs_initgtm -D %s -Z gtm %s" % \
                      (self.binPath, self.instInfo.datadir, " ".join(self.__gtmParams))
            self.logger.debug("Command for initializing instance: %s" % cmd)
            (status, output) = DefaultValue.retryGetstatusoutput(cmd)
            if status != 0:
                raise Exception(ErrorCode.GAUSS_516["GAUSS_51615"] + " Command:%s. Error:\n%s" % (cmd, output))
        except Exception as e:
            raise Exception(str(e))

    def uninstall(self):
        """
        function: uninstall the GTM component
        input : NA
        output: NA
        """
        datadir = self.instInfo.datadir
        if os.path.exists(datadir):
            g_file.cleanDirectoryContent(datadir)

    def configInstance(self, clusterInfo, user=None, configItemType=None, alarm_component=None, dwsMode=False):
        """
        function: config the GTM component
        input : NA
        output: NA
        """
        instList = clusterInfo.getPeerInstance(self.instInfo)
        if clusterInfo.isMasterStandbyCluster() or clusterInfo.isMasterStandbyMultiAZCluster():
            if len(instList) != 1:
                raise Exception(ErrorCode.GAUSS_516["GAUSS_51605"] % "gtm")

        peerGtm = instList
        tmpGTMDict = self.getGTMDict(peerGtm, user, configItemType, alarm_component, dwsMode)
        # for Single Primary Multi Standby Cluster the para active_host must be null
        configFile = os.path.join(self.instInfo.datadir, "gtm.conf")
        ClusterInstanceConfig.setConfigItem(DefaultValue.INSTANCE_ROLE_GTM, self.instInfo.datadir, configFile,
                                            tmpGTMDict)

    def getGTMDict(self, peerGtm, user=None, configItemType=None, alarm_component=None, dwsMode=False):
        """
        function: Get GTM configuration
        input : peerGtm is empty means that this is a single cluster.
        output: NA
        """
        tmpGTMDict = {"listen_addresses": "'localhost,%s'" % ",".join(self.instInfo.listenIps),
                      "port": str(self.instInfo.port), "nodename": "'gtm_%s'" % str(self.instInfo.instanceId)}
        if configItemType != "ChangeIPUtility":
            tmpGTMDict["log_directory"] = "'%s/pg_log/gtm'" % (DefaultValue.getUserLogDirWithUser(user))
        if peerGtm:
            tmpGTMDict["local_host"] = "'%s'" % ",".join(self.instInfo.haIps)
            tmpGTMDict["local_port"] = str(self.instInfo.haPort)
            if self.clusterType != DefaultValue.CLUSTER_TYPE_SINGLE_PRIMARY_MULTI_STANDBY:
                tmpGTMDict["active_host"] = "'%s'" % ",".join(peerGtm[0].haIps)
                tmpGTMDict["active_port"] = str(peerGtm[0].haPort)
        if configItemType == "ConfigInstance":
            tmpGTMDict["alarm_component"] = "'%s'" % alarm_component
        if dwsMode:
            tmpGTMDict["enable_connect_control"] = "off"
        return tmpGTMDict
