'Copy the page and all its plugins and descendants to the requested
target, at the given position
NOTE: We have to change from one "coordinate system" to another to
adapt JSTree to Django Treebeard. See comments in move_page().
NOTE: This code handles more cases then are *currently* supported in
the UI, specifically, the target should never be None and the position
should never be non-zero. These are implemented, however, because we
intend to support these cases later.'

@require_POST
@transaction.atomic
def copy_page(self, request, page_id, extra_context=None):

    target = request.POST.get('target', None)
    position = request.POST.get('position', None)
    site_id = request.POST.get('site', None)
    copy_permissions = request.POST.get('copy_permissions', False)
    try:
        page = self.model.objects.get(pk=page_id)
    except self.model.DoesNotExist:
        return jsonify_request(HttpResponseBadRequest('Error'))
    try:
        position = int(position)
    except (TypeError, ValueError):
        position = 0
    try:
        site = Site.objects.get(id=int(site_id))
    except (TypeError, ValueError, MultipleObjectsReturned, ObjectDoesNotExist):
        site = get_current_site(request)
    if (target is None):
        try:
            tb_target = Page.get_draft_root_node(position=position, site=site)
            tb_position = 'left'
        except IndexError:
            tb_target = Page.get_draft_root_node(site=site)
            tb_position = 'right'
    else:
        try:
            tb_target = self.model.objects.get(pk=int(target), site=site)
            assert tb_target.has_add_permission(request.user)
        except (TypeError, ValueError, self.model.DoesNotExist, AssertionError):
            return jsonify_request(HttpResponseBadRequest('Error'))
        if (position == 0):
            tb_position = 'first-child'
        else:
            try:
                tb_target = tb_target.get_children().filter(publisher_is_draft=True, site=site)[position]
                tb_position = 'left'
            except IndexError:
                tb_position = 'last-child'
    try:
        new_page = page.copy_page(tb_target, site, tb_position, copy_permissions=copy_permissions)
        results = {'id': new_page.pk}
        return HttpResponse(json.dumps(results), content_type='application/json')
    except ValidationError:
        exc = sys.exc_info()[1]
        return jsonify_request(HttpResponseBadRequest(exc.messages))
