#
# Copyright 2019 VMware, Inc.  All rights reserved. -- VMware Confidential
#

import ssl
import logging
import os, sys
sys.path.append(os.path.dirname(__file__))
sys.path.append(os.environ['VMWARE_PYTHON_PATH'])

from pyVmomi import SoapStubAdapter  #pylint: disable=E0401
from pyVim.connect import VimSessionOrientedStub #pylint: disable=E0401

logger = logging.getLogger(__name__)

DEFAULT_HTTPS_PORT = 443


class ServiceStub:
    def __init__(self, host, username=None, password=None,
                 cert_file=None, key_file=None, sts_url=None,
                 port=DEFAULT_HTTPS_PORT, namespace=None,
                 path="/sdk", no_ssl_verification=False):
        self.host = host
        self.port = port

        if username is not None and password is not None:
            login_method = \
                VimSessionOrientedStub.makeUserLoginMethod(username, password)
        elif cert_file is not None and key_file is not None \
                and sts_url is not None:
            login_method = \
                VimSessionOrientedStub.makeCertHokTokenLoginMethod(sts_url)
        else:
            raise ValueError("Invalid arguments passed to ServiceStub")

        context = None
        if no_ssl_verification:
            context = ssl._create_unverified_context()

        soap_stub = SoapStubAdapter(host=host, ns=namespace, certFile=cert_file,
                                    certKeyFile=key_file, path=path,
                                    sslContext=context, port=self.port)
        self._stub = VimSessionOrientedStub(soap_stub, login_method)

    @property
    def stub(self):
        """
        Gets stub for a remote service instance object.
        :return: An instance of a remote service stub
        """
        return self._stub
