def update_publish_draft(request):
    form_id = request.GET['draft_id']
    form_data = FormData.objects.get(pk=form_id)
    xml_string = form_data.xml_data
    title = form_data.name
    if xml_string == "" or xml_string is None:
        return HttpResponseBadRequest('No XML data found')
    try:
        # update form data if id is present
        if form_data.xml_data_id is not None:
            publicationdate = XMLdata.update_publish_draft(form_data.xml_data_id, xml_string, str(request.user.id))
            #Delete the form
            if form_data.schema_element_root is not None:
                delete_branch_from_db(form_data.schema_element_root.pk)
            form_data.delete()

            # Send mail to the managers
            context = {'URI': MDCS_URI,
                       'title': title,
                       'publicationdate': publicationdate,
                       'user': request.user.username}

            send_mail_to_managers(subject='Resource Published',
                                    pathToTemplate='dashboard/email/resource_published.html',
                                    context=context)

            messages.add_message(request, messages.INFO, 'New version published with success.')
            return HttpResponse(json.dumps({}), content_type='application/javascript')
        else:
            return HttpResponseBadRequest('Related record not found. Impossible to publish the draft')

    except Exception, e:
        message = e.message.replace('"', '\'')
        return HttpResponseBadRequest(message)
def generate_xsd_form(request):
    """ Renders HTMl form for display.

    Parameters:
        request:

    Returns:
        str: HTML form
    """
    try:
        if 'form_id' in request.session:
            root_element_id = request.session['form_id']
            form_data = None
            request.session['curate_edit'] = False
        else:  # If this is a new form, generate it and store the root ID
            # get the xsd tree when going back and forth with review step
            if 'xmlDocTree' in request.session:
                xsd_doc_data = request.session['xmlDocTree']
            else:
                template_id = request.session['currentTemplateID']
                template_object = Template.objects.get(pk=template_id)
                xsd_doc_data = template_object.content

            # get form data from the database (empty one or existing one)
            form_data_id = request.session['curateFormData']
            form_data = FormData.objects.get(pk=ObjectId(form_data_id))

            if form_data.xml_data is not None:
                xml_doc_data = form_data.xml_data
            else:
                xml_doc_data = None

            root_element_id = generate_form(request, xsd_doc_data, xml_doc_data, config=load_config())
            request.session['form_id'] = str(root_element_id)

        root_element = SchemaElement.objects.get(pk=root_element_id)

        if form_data is not None:
            if form_data.schema_element_root is not None:
                delete_branch_from_db(form_data.schema_element_root.pk)

            form_data.update(set__schema_element_root=root_element)
            form_data.reload()

        renderer = ListRenderer(root_element, request)
        html_form = renderer.render()
    except Exception as e:
        renderer = DefaultRenderer(SchemaElement(), {})

        if e.message is not None:
            err_message = e.message
        else:
            err_message = "An unknown error raised " + e.__class__.__name__

        html_form = renderer._render_form_error(err_message)

    return HttpResponse(json.dumps({'xsdForm': html_form}), content_type='application/javascript')
def remove_element(request):
    element_id = request.POST['id']
    # sub_element = SchemaElement.objects.get(pk=element_id)
    element_list = SchemaElement.objects(children=element_id)

    if len(element_list) == 0:
        raise ValueError("No SchemaElement found")
    elif len(element_list) > 1:
        raise ValueError("More than one SchemaElement found")

    # Removing the element from the data structure
    schema_element = element_list[0]
    schema_element.update(pull__children=element_id)

    schema_element.reload()
    update_branch_xpath(schema_element)

    # Deleting the branch from the database
    delete_branch_from_db(element_id)

    children_number = len(schema_element.children)

    # TODO Move it to parser function
    # FIXME Sequence elem it might not work
    if len(schema_element.children) == 0:
        elem_iter = SchemaElement()

        if schema_element.tag == 'element':
            elem_iter.tag = 'elem-iter'
        elif schema_element.tag == 'choice':
            elem_iter.tag = 'choice-iter'
        elif schema_element.tag == 'sequence':
            elem_iter.tag = 'sequence-iter'

        elem_iter.save()
        schema_element.update(add_to_set__children=[elem_iter])
        schema_element.reload()

    response = {
        'code': 0,
        'html': ""
    }

    if children_number > schema_element.options['min']:
        return HttpResponse(json.dumps(response), status=HTTP_200_OK)
    else:  # len(schema_element.children) == schema_element.options['min']
        if schema_element.options['min'] != 0:
            response['code'] = 1
        else:  # schema_element.options['min'] == 0
            renderer = ListRenderer(schema_element, request)
            html_form = renderer.render(True)

            response['code'] = 2
            response['html'] = html_form

        return HttpResponse(json.dumps(response))
def delete_form(request):
    if 'id' in request.GET:
        form_data_id = request.GET['id']
        try:
            form_data = FormData.objects().get(pk=form_data_id)
            # TODO: check if need to delete all SchemaElements
            if form_data.schema_element_root is not None:
                delete_branch_from_db(form_data.schema_element_root.pk)

            form_data.delete()

            messages.add_message(request, messages.INFO, 'Form deleted with success.')
        except Exception, e:
            return HttpResponse({}, status=400)
def cancel_form(request):
    try:
        form_data_id = request.session['curateFormData']
        form_data = FormData.objects().get(pk=form_data_id)
        # TODO: check if need to delete all schema elements

        if form_data.schema_element_root is not None:
            delete_branch_from_db(form_data.schema_element_root.pk)

        form_data.delete()
        messages.add_message(request, messages.INFO, 'Form deleted with success.')
        return HttpResponse({},status=204)
    except Exception, e:
        return HttpResponse({},status=400)