# Copyright 2010 OpenStack Foundation
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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 functools
import logging
import os
import sys
import time

from glanceclient import client
from oslo_config import cfg
import sendfile
import six.moves.urllib.parse as urlparse

from ironic.common import exception
from ironic.common.glance_service import service_utils
from ironic.common.i18n import _LE


LOG = logging.getLogger(__name__)
CONF = cfg.CONF


def _translate_image_exception(image_id, exc_value):
    if isinstance(exc_value, (exception.Forbidden,
                              exception.Unauthorized)):
        return exception.ImageNotAuthorized(image_id=image_id)
    if isinstance(exc_value, exception.NotFound):
        return exception.ImageNotFound(image_id=image_id)
    if isinstance(exc_value, exception.BadRequest):
        return exception.Invalid(exc_value)
    return exc_value


def _translate_plain_exception(exc_value):
    if isinstance(exc_value, (exception.Forbidden,
                              exception.Unauthorized)):
        return exception.NotAuthorized(exc_value)
    if isinstance(exc_value, exception.NotFound):
        return exception.NotFound(exc_value)
    if isinstance(exc_value, exception.BadRequest):
        return exception.Invalid(exc_value)
    return exc_value


def check_image_service(func):
    """Creates a glance client if doesn't exists and calls the function."""
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        """Wrapper around methods calls.

        :param image_href: href that describes the location of an image