from endpoints.api import (resource, nickname, require_repo_read, require_repo_admin,
                           RepositoryParamResource, log_action, NotFound)
from endpoints.api.image import image_view
from data import model
from auth.auth_context import get_authenticated_user


@resource('/v1/repository/<repopath:repository>/tag/<tag>')
class RepositoryTag(RepositoryParamResource):
  """ Resource for managing repository tags. """

  @require_repo_admin
  @nickname('deleteFullTag')
  def delete(self, namespace, repository, tag):
    """ Delete the specified repository tag. """
    model.delete_tag(namespace, repository, tag)
    model.garbage_collect_repository(namespace, repository)

    username = get_authenticated_user().username
    log_action('delete_tag', namespace,
               {'username': username, 'repo': repository, 'tag': tag},
               repo=model.get_repository(namespace, repository))

    return 'Deleted', 204


@resource('/v1/repository/<repopath:repository>/tag/<tag>/images')
class RepositoryTagImages(RepositoryParamResource):
  """ Resource for listing the images in a specific repository tag. """
  @require_repo_read
  @nickname('listTagImages')
  def get(self, namespace, repository, tag):
    """ List the images for the specified repository tag. """
    try:
      tag_image = model.get_tag_image(namespace, repository, tag)
    except model.DataModelException:
      raise NotFound()

    parent_images = model.get_parent_images(tag_image)

    parents = list(parent_images)
    parents.reverse()
    all_images = [tag_image] + parents

    return {
      'images': [image_view(image) for image in all_images]
    }