import logging

from functools import wraps
from urlparse import urlparse

from flask import Blueprint, make_response, url_for, request, jsonify
from semantic_version import Spec

import features

from app import app, metric_queue
from auth.auth_context import get_grant_context
from auth.permissions import (ReadRepositoryPermission, ModifyRepositoryPermission,
                              AdministerRepositoryPermission)
from auth.registry_jwt_auth import process_registry_jwt_auth, get_auth_headers
from data import model
from endpoints.decorators import anon_protect, anon_allowed
from endpoints.v2.errors import V2RegistryException, Unauthorized
from util.http import abort
from util.registry.dockerver import docker_version
from util.metrics.metricqueue import time_blueprint

logger = logging.getLogger(__name__)
v2_bp = Blueprint('v2', __name__)

time_blueprint(v2_bp, metric_queue)

@v2_bp.app_errorhandler(V2RegistryException)
def handle_registry_v2_exception(error):
  response = jsonify({
    'errors': [error.as_dict()]
  })

  response.status_code = error.http_status_code
  if response.status_code == 401:
    response.headers.extend(get_auth_headers(repository=error.repository, scopes=error.scopes))
  logger.debug('sending response: %s', response.get_data())
  return response


def _require_repo_permission(permission_class, scopes=None, allow_public=False):
  def wrapper(func):
    @wraps(func)
    def wrapped(namespace_name, repo_name, *args, **kwargs):
      logger.debug('Checking permission %s for repo: %s/%s', permission_class,
                   namespace_name, repo_name)
      permission = permission_class(namespace_name, repo_name)
      if (permission.can() or
          (allow_public and
           model.repository.repository_is_public(namespace_name, repo_name))):
        return func(namespace_name, repo_name, *args, **kwargs)
      repository = namespace_name + '/' + repo_name
      raise Unauthorized(repository=repository, scopes=scopes)
    return wrapped
  return wrapper


require_repo_read = _require_repo_permission(ReadRepositoryPermission,
                                             scopes=['pull'],
                                             allow_public=True)
require_repo_write = _require_repo_permission(ModifyRepositoryPermission,
                                              scopes=['pull', 'push'])
require_repo_admin = _require_repo_permission(AdministerRepositoryPermission,
                                              scopes=['pull', 'push'])


def get_input_stream(flask_request):
  if flask_request.headers.get('transfer-encoding') == 'chunked':
    return flask_request.environ['wsgi.input']
  return flask_request.stream


# TODO remove when v2 is deployed everywhere
def route_show_if(value):
  def decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
      if not value:
        abort(404)

      return f(*args, **kwargs)
    return decorated_function
  return decorator

@v2_bp.route('/')
@route_show_if(features.ADVERTISE_V2)
@process_registry_jwt_auth()
@anon_allowed
def v2_support_enabled():
  docker_ver = docker_version(request.user_agent.string)

  # Check if our version is one of the blacklisted versions, if we can't
  # identify the version (None) we will fail open and assume that it is
  # newer and therefore should not be blacklisted.
  if Spec(app.config['BLACKLIST_V2_SPEC']).match(docker_ver) and docker_ver is not None:
    abort(404)

  response = make_response('true', 200)

  if get_grant_context() is None:
    response = make_response('true', 401)

  response.headers.extend(get_auth_headers())
  return response


from endpoints.v2 import v2auth
from endpoints.v2 import manifest
from endpoints.v2 import blob
from endpoints.v2 import tag
from endpoints.v2 import catalog