# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Dimension Data Common Components
"""
from base64 import b64encode
from time import sleep
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import b
from libcloud.common.base import ConnectionUserAndKey, XmlResponse
from libcloud.common.types import LibcloudError, InvalidCredsError
from libcloud.compute.base import Node
from libcloud.utils.py3 import basestring
from libcloud.utils.xml import findtext

# Roadmap / TODO:
#
# 1.0 - Copied from OpSource API, named provider details.

# setup a few variables to represent all of the DimensionData cloud namespaces
NAMESPACE_BASE = "http://oec.api.opsource.net/schemas"
ORGANIZATION_NS = NAMESPACE_BASE + "/organization"
SERVER_NS = NAMESPACE_BASE + "/server"
NETWORK_NS = NAMESPACE_BASE + "/network"
DIRECTORY_NS = NAMESPACE_BASE + "/directory"
GENERAL_NS = NAMESPACE_BASE + "/general"
BACKUP_NS = NAMESPACE_BASE + "/backup"

# API 2.0 Namespaces and URNs
TYPES_URN = "urn:didata.com:api:cloud:types"

# API end-points
API_ENDPOINTS = {
    'dd-na': {
        'name': 'North America (NA)',
        'host': 'api-na.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'dd-eu': {
        'name': 'Europe (EU)',
        'host': 'api-eu.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'dd-au': {
        'name': 'Australia (AU)',
        'host': 'api-au.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'dd-au-gov': {
        'name': 'Australia Canberra ACT (AU)',
        'host': 'api-canberra.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'dd-af': {
        'name': 'Africa (AF)',
        'host': 'api-mea.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'dd-ap': {
        'name': 'Asia Pacific (AP)',
        'host': 'api-ap.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'dd-latam': {
        'name': 'South America (LATAM)',
        'host': 'api-latam.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'dd-canada': {
        'name': 'Canada (CA)',
        'host': 'api-canada.dimensiondata.com',
        'vendor': 'DimensionData'
    },
    'is-na': {
        'name': 'North America (NA)',
        'host': 'usapi.cloud.is.co.za',
        'vendor': 'InternetSolutions'
    },
    'is-eu': {
        'name': 'Europe (EU)',
        'host': 'euapi.cloud.is.co.za',
        'vendor': 'InternetSolutions'
    },
    'is-au': {
        'name': 'Australia (AU)',
        'host': 'auapi.cloud.is.co.za',
        'vendor': 'InternetSolutions'
    },
    'is-af': {
        'name': 'Africa (AF)',
        'host': 'meaapi.cloud.is.co.za',
        'vendor': 'InternetSolutions'
    },
    'is-ap': {
        'name': 'Asia Pacific (AP)',
        'host': 'apapi.cloud.is.co.za',
        'vendor': 'InternetSolutions'
    },
    'is-latam': {
        'name': 'South America (LATAM)',
        'host': 'latamapi.cloud.is.co.za',
        'vendor': 'InternetSolutions'
    },
    'is-canada': {
        'name': 'Canada (CA)',
        'host': 'canadaapi.cloud.is.co.za',
        'vendor': 'InternetSolutions'
    },
    'ntta-na': {
        'name': 'North America (NA)',
        'host': 'cloudapi.nttamerica.com',
        'vendor': 'NTTNorthAmerica'
    },
    'ntta-eu': {
        'name': 'Europe (EU)',
        'host': 'eucloudapi.nttamerica.com',
        'vendor': 'NTTNorthAmerica'
    },
    'ntta-au': {
        'name': 'Australia (AU)',
        'host': 'aucloudapi.nttamerica.com',
        'vendor': 'NTTNorthAmerica'
    },
    'ntta-af': {
        'name': 'Africa (AF)',
        'host': 'sacloudapi.nttamerica.com',
        'vendor': 'NTTNorthAmerica'
    },
    'ntta-ap': {
        'name': 'Asia Pacific (AP)',
        'host': 'hkcloudapi.nttamerica.com',
        'vendor': 'NTTNorthAmerica'
    },
    'cisco-na': {
        'name': 'North America (NA)',
        'host': 'iaas-api-na.cisco-ccs.com',
        'vendor': 'Cisco'
    },
    'cisco-eu': {
        'name': 'Europe (EU)',
        'host': 'iaas-api-eu.cisco-ccs.com',
        'vendor': 'Cisco'
    },
    'cisco-au': {
        'name': 'Australia (AU)',
        'host': 'iaas-api-au.cisco-ccs.com',
        'vendor': 'Cisco'
    },
    'cisco-af': {
        'name': 'Africa (AF)',
        'host': 'iaas-api-mea.cisco-ccs.com',
        'vendor': 'Cisco'
    },
    'cisco-ap': {
        'name': 'Asia Pacific (AP)',
        'host': 'iaas-api-ap.cisco-ccs.com',
        'vendor': 'Cisco'
    },
    'cisco-latam': {
        'name': 'South America (LATAM)',
        'host': 'iaas-api-sa.cisco-ccs.com',
        'vendor': 'Cisco'
    },
    'cisco-canada': {
        'name': 'Canada (CA)',
        'host': 'iaas-api-ca.cisco-ccs.com',
        'vendor': 'Cisco'
    },
    'med1-il': {
        'name': 'Israel (IL)',
        'host': 'api.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'med1-na': {
        'name': 'North America (NA)',
        'host': 'api-na.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'med1-eu': {
        'name': 'Europe (EU)',
        'host': 'api-eu.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'med1-au': {
        'name': 'Australia (AU)',
        'host': 'api-au.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'med1-af': {
        'name': 'Africa (AF)',
        'host': 'api-af.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'med1-ap': {
        'name': 'Asia Pacific (AP)',
        'host': 'api-ap.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'med1-latam': {
        'name': 'South America (LATAM)',
        'host': 'api-sa.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'med1-canada': {
        'name': 'Canada (CA)',
        'host': 'api-ca.cloud.med-1.com',
        'vendor': 'Med-1'
    },
    'indosat-id': {
        'name': 'Indonesia (ID)',
        'host': 'iaas-api.indosat.com',
        'vendor': 'Indosat'
    },
    'indosat-na': {
        'name': 'North America (NA)',
        'host': 'iaas-usapi.indosat.com',
        'vendor': 'Indosat'
    },
    'indosat-eu': {
        'name': 'Europe (EU)',
        'host': 'iaas-euapi.indosat.com',
        'vendor': 'Indosat'
    },
    'indosat-au': {
        'name': 'Australia (AU)',
        'host': 'iaas-auapi.indosat.com',
        'vendor': 'Indosat'
    },
    'indosat-af': {
        'name': 'Africa (AF)',
        'host': 'iaas-afapi.indosat.com',
        'vendor': 'Indosat'
    },
    'bsnl-in': {
        'name': 'India (IN)',
        'host': 'api.bsnlcloud.com',
        'vendor': 'BSNL'
    },
    'bsnl-na': {
        'name': 'North America (NA)',
        'host': 'usapi.bsnlcloud.com',
        'vendor': 'BSNL'
    },
    'bsnl-eu': {
        'name': 'Europe (EU)',
        'host': 'euapi.bsnlcloud.com',
        'vendor': 'BSNL'
    },
    'bsnl-au': {
        'name': 'Australia (AU)',
        'host': 'auapi.bsnlcloud.com',
        'vendor': 'BSNL'
    },
    'bsnl-af': {
        'name': 'Africa (AF)',
        'host': 'afapi.bsnlcloud.com',
        'vendor': 'BSNL'
    },
}

# Default API end-point for the base connection class.
DEFAULT_REGION = 'dd-na'

BAD_CODE_XML_ELEMENTS = (
    ('responseCode', SERVER_NS),
    ('responseCode', TYPES_URN),
    ('result', GENERAL_NS)
)

BAD_MESSAGE_XML_ELEMENTS = (
    ('message', SERVER_NS),
    ('message', TYPES_URN),
    ('resultDetail', GENERAL_NS)
)


def dd_object_to_id(obj, obj_type, id_value='id'):
    """
    Takes in a DD object or string and prints out it's id
    This is a helper method, as many of our functions can take either an object
    or a string, and we need an easy way of converting them

    :param obj: The object to get the id for
    :type  obj: ``object``

    :param  func: The function to call, e.g. ex_get_vlan. Note: This
                  function needs to return an object which has ``status``
                  attribute.
    :type   func: ``function``

    :rtype: ``str``
    """
    if isinstance(obj, obj_type):
        return getattr(obj, id_value)
    elif isinstance(obj, (basestring)):
        return obj
    else:
        raise TypeError(
            "Invalid type %s looking for basestring or %s"
            % (type(obj).__name__, obj_type.__name__)
        )


class NetworkDomainServicePlan(object):
    ESSENTIALS = "ESSENTIALS"
    ADVANCED = "ADVANCED"


class DimensionDataResponse(XmlResponse):
    def parse_error(self):
        if self.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError(self.body)
        elif self.status == httplib.FORBIDDEN:
            raise InvalidCredsError(self.body)

        body = self.parse_body()

        if self.status == httplib.BAD_REQUEST:
            for response_code in BAD_CODE_XML_ELEMENTS:
                code = findtext(body, response_code[0], response_code[1])
                if code is not None:
                    break
            for message in BAD_MESSAGE_XML_ELEMENTS:
                message = findtext(body, message[0], message[1])
                if message is not None:
                    break
            raise DimensionDataAPIException(code=code,
                                            msg=message,
                                            driver=self.connection.driver)
        if self.status is not httplib.OK:
            raise DimensionDataAPIException(code=self.status,
                                            msg=body,
                                            driver=self.connection.driver)

        return self.body


class DimensionDataAPIException(LibcloudError):
    def __init__(self, code, msg, driver):
        self.code = code
        self.msg = msg
        self.driver = driver

    def __str__(self):
        return "%s: %s" % (self.code, self.msg)

    def __repr__(self):
        return ("<DimensionDataAPIException: code='%s', msg='%s'>" %
                (self.code, self.msg))


class DimensionDataConnection(ConnectionUserAndKey):