# Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
#    Licensed 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.

import httplib2
import logging
import os
import time
import urlparse
import sys

try:
    import json
except ImportError:
    import simplejson as json

# Python 2.5 compat fix
if not hasattr(urlparse, 'parse_qsl'):
    import cgi
    urlparse.parse_qsl = cgi.parse_qsl

from troveclient.compat import auth
from troveclient.compat import exceptions


_logger = logging.getLogger(__name__)
RDC_PP = os.environ.get("RDC_PP", "False") == "True"


expected_errors = (400, 401, 403, 404, 408, 409, 413, 422, 500, 501)


def log_to_streamhandler(stream=None):
    stream = stream or sys.stderr
    ch = logging.StreamHandler(stream)
    _logger.setLevel(logging.DEBUG)
    _logger.addHandler(ch)


if 'REDDWARFCLIENT_DEBUG' in os.environ and os.environ['REDDWARFCLIENT_DEBUG']:
    log_to_streamhandler()


class TroveHTTPClient(httplib2.Http):

    USER_AGENT = 'python-troveclient'

    def __init__(self, user, password, tenant, auth_url, service_name,
                 service_url=None,
                 auth_strategy=None, insecure=False,
                 timeout=None, proxy_tenant_id=None,
                 proxy_token=None, region_name=None,
                 endpoint_type='publicURL', service_type=None,
                 timings=False):

        super(TroveHTTPClient, self).__init__(timeout=timeout)

        self.username = user
        self.password = password