# Copyright 2020-2022 VMware, Inc.  All rights reserved. -- VMware Confidential
# Description: Provides class NsxtMgrRest
# Disabled: True
#
#  nsxt_mgr_rest.py
#
#

import json
import logging
import pprint
import subprocess
import traceback
import urllib.parse


logger = logging.getLogger(__name__)


class NsxtMgrRest:
    """
    Helper for accessing (get, delete, CLI) the Nsxt Manager.
    """

    def __init__(self, nsxtCred):
        self.nsxtCred = nsxtCred

    def _nsxtRelToAbsUrl(self, relUrl):
        slashDelim = "" if relUrl.startswith("/") else "/"
        absUrl = ("https://" + self.nsxtCred.ipAddr + slashDelim +
                  urllib.parse.quote(relUrl))
        return absUrl

    def _nsxtBaseCurlCmd(self):
        return ["curl", "-s", "--insecure",
                "-u", "%s:%s" % (self.nsxtCred.username,
                                 self.nsxtCred.password),
                "-H", "Accept:application/json",
                "-H", "Content-Type:application/json"]

    def nsxtGet(self, relUrl, errorOk=False):
        """Return JSON results, parsed to a dict, from querying the specified URL
        relative URL on the NSX-T Manager.

        errorOk : bool
            If True, tolerate request errors which would normally be fatal.
        """

        # NB: we don't know what REST libraries are available in all our
        #     target platforms (SDDC Mgr, or any other host with password-free
        #     access to SDDC Mgr) so we use curl for REST operations.

        absUrl = self._nsxtRelToAbsUrl(relUrl)

        cmd = self._nsxtBaseCurlCmd() + [absUrl]

        try:
            outText = subprocess.check_output(cmd)
            outJson = json.loads(outText)
        except Exception:
            logger.error("Failed to query %s, stopping now." % relUrl)

        if (('httpStatus' in outJson) and
                (outJson['httpStatus'] == 'NOT_FOUND')):
            return None

        if ('error_code' in outJson) or ('error_message' in outJson):
            pp = pprint.PrettyPrinter()
            logger.error("Error during NSX-T query of %s" % relUrl)
            logger.error("Reported by NSX-T manager at %s:" %
                         self.nsxtCred.ipAddr)
            logger.error(pp.pformat(outJson))

            if errorOk:
                # return a dummy, empty result
                outJson = {}
            else:
                traceback.print_stack()
                self._stopNow()

        return outJson

    def nsxtGetList(self, relUrl, filterLambda=None, errorOk=False):
        """Same as get(), but returns just the results of a list operation.
        If present, we use the caller-supplied lambda to filter the list to
        only those entries which match the lambda's filter condition.

        errorOk : bool
            If True, tolerate request errors which would normally be fatal.
        """
        response = self.nsxtGet(relUrl, errorOk=errorOk)
        if "results" in response:
            listOut = response["results"]
        else:
            listOut = []

        if filterLambda:
            listOut = list(filter(filterLambda, listOut))

        return listOut
