{% import 'macros/form.html' as form %}

{#{% resource 'baepublisher/image_upload.js' %}#}
{% set private = data.get('private') %}

{% set name = offering.title if offering.title else data["title"] %}
{% set start_datetime = offering.contract_start if offering.contract_start else c.current_date_time %}
{% set end_datetime = offering.contract_end if offering.contract_end else '' %}
{% set offering_data = {
    'contract_start' : start_datetime,
    'contract_end' : end_datetime,
    'title' : name
            } %}

{% set price = offering['price'] if offering else '' %}
{% set is_open = offering['is_open'] if offering else True %}
{% set update_acquire_url = offering['update_acquire_url'] if offering else True %}
{% set catalogs = offering['catalogs'] %}
{% set role = offering['role'] if offering else '' %}

{# This provides a full page that renders a form for publishing a dataset. It can
then itself be extended to add/remove blocks of functionality. #}
<form class="dataset-form row" method="post" data-module="basic-form" action enctype="multipart/form-data">

    {% block errors %}
        {% if errors %}
            <div class="error-explanation alert alert-error">
                <p>{{ _('The offering could not be published:') }}</p>
                <ul>
                    {% for key, error in errors.items() %}
                        <li data-field-label="{{ key }}">{% if key %}{{ key }}: {% endif %}{{ error[0] }}</li>
                    {% endfor %}
                </ul>
            </div>
        {% endif %}
    {% endblock %}

    <input type="hidden" name="pkg_id" value="{{ data.id }}"/>

    <h2>Contract Basic Info</h2>
    <div class="panel panel-default">
        <div class="panel-body">
            {% block offering_title %}
                {{ form.input('title', id='title', label=_('Title'), placeholder=_('eg. The title of the offering'), value=name, error=errors['name'], classes=['control-full', 'control-large', 'col-md-12'], is_required=true) }}
            {% endblock %}

            {% block start_datetime %}
                {%- set start_datetime_field = {
                                  'field_name' : 'contract_start',
                                  'label' : 'Contract start',
                                  'validators' : 'scheming_isodatetime_tz convert_to_json_if_datetime',
                                  'required' : True
                                  }
                -%}
                {%- snippet 'scheming/form_snippets/datetime_tz.html',
                                          field=start_datetime_field,
                                          data=offering_data,
                                          errors=errors,
                                          licenses=licenses,
                                          entity_type='dataset',
                                          object_type='contract'
                -%}
            {% endblock %}

            {% block end_datetime %}
                {%- set end_datetime_field = {
                  'field_name' : 'contract_end',
                  'label': 'Contract end',
                  'validators' : 'scheming_isodatetime_tz convert_to_json_if_datetime',
                  'required': True
                  }
                -%}
                {%- snippet 'scheming/form_snippets/datetime_tz.html',
                          field=end_datetime_field,
                          data=offering_data,
                          errors=errors,
                          licenses=licenses,
                          entity_type='dataset',
                          object_type='contract'
                -%}
            {% endblock %}
        </div>
    </div>


    <h2>Choose usage policies: </h2>
    {% block usage_control %}
        <div>
            {% for policy in usage_control_policies.policy_templates %}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        {%- set attributes = {"onchange":"enableUsagePolicyOptions(this)"} -%}
                        {% set label = policy["label"][h.lang()]  %}
                        {% set description = policy["description"][h.lang()]  %}
                        {{ form.checkbox(policy.type, label=label, checked=false, attrs=attributes) }}
                    </div>
                    <div class="panel-body">
                    <p>{{ description }}</p>
                    {%- if  policy['fields']|length != 0 -%}
                            {% for field in policy.fields %}
                                {%- snippet 'scheming/form_snippets/' + field.form_snippet,
                                                            field=field,
                                                            data=offering_data,
                                                            errors=errors,
                                                            entity_type='dataset',
                                                            object_type='contract'
                                -%}
                            {% endfor %}
                    {% endif %}
                    </div>
                </div>
            {% endfor %}
        </div>
    {% endblock %}

    {#

    {% block offering_description %}
        {{ form.textarea('description', id='field-description', classes=['col-md-12'], label=_('Description'), placeholder=_('eg. Offering description'), value=description, error=errors.notes) }}
    {% endblock %}
#}

    {#

    {% block offering_tags %}
        {% set category_attrs = {'data-module': 'autocomplete', 'data-module-tags': '',
  'data-module-source': '/api/2/util/tag/autocomplete?incomplete=?', 'multiple':
  true} %}
        {{ form.select('categories', id='field-category', label=_('Categories'), options=categories, error=errors.categories, classes=['control-full'], attrs=category_attrs) }}
    {% endblock %}

    {% block offering_catalogs %}
        {% set catalog_attrs = {'data-module': 'autocomplete', 'data-module-tags': '',
  'data-module-source': '/api/2/util/tag/autocomplete?incomplete=?' } %}
        {{ form.select('catalogs', id='field-catalogs', label=_('Catalogs'), options=catalogs, error=errors.catalogs, classes=['control-full'], attrs=catalog_attrs) }}
    {% endblock %}

    {% block offering_version %}
        {{ form.input('version', id='field-version', label=_('Version'), placeholder=_('eg. 1.0, 2.3.4'), value=version, classes=['control-full', 'control-medium'], is_required=true) }}
    {% endblock %}

    {% block offering_license_title %}
        {{ form.input('license_title', id='field-license_title', label=_('License'), placeholder=_('eg. Creative Commons Attribution'), value=license_title, classes=['control-full', 'control-medium']) }}
    {% endblock %}

    {% block offering_license_description %}
        {{ form.textarea('license_description', id='field-license_description', label=_('License Description'), placeholder=_('License description. You can find license definitions at opendefinition.org'), value=license_description, error=errors.notes) }}
    {% endblock %}

    {% block offering_role %}
        {{ form.input('role', id='field-role', label=_('Acquisition Role'), placeholder=_('eg. query_customer'), value=role, classes=['control-full', 'control-medium']) }}
    {% endblock %}

    {% block image %}
        <div class="control-group control-full" style="display: block;">
            <label class="control-label" for="field-image_upload">{% trans %}Image{% endtrans %}</label>
            <div class="controls ">
                <input id="field-image_upload" type="file" name="image_upload" value="" placeholder="" title="Upload a file on your computer" style="display: none;">
                <a id="button-upload" href="javascript:;" class="btn" style="display: inline-block;">
                    <i class="icon-cloud-upload fa fa-cloud-upload"></i>{% trans %}Upload{% endtrans %}
                </a>
                <a id="button-remove" href="javascript:;" class="btn btn-danger" style="display: none;">{% trans %}Remove{% endtrans %}
                </a>
                <span class="info-block info-inline">
          <i class="icon-info-sign fa-info-circle"></i>
                    {% trans %}
                        Attach an image to the offering. If you do not upload an image, a default one will be used.
                    {% endtrans %}
        </span>
            </div>
        </div>
    {% endblock %}

    {% if not private %}
        {% block offering_open %}
            <div class="control-group ">
                <div class="controls">
                    <label class="checkbox" for="field-open">
                        <input id="field-open" type="checkbox" name="open" value="" {{ "checked " if is_open }}>
                        {% trans %}Open Offering{% endtrans %}
                        <span class="info-block info-inline" style="font-weight: normal;">
              <i class="icon-info-sign fa fa-info-circle"></i>
                            {% trans %}
                                Open Offerings cannot be acquired so their resources are public by default. Non-open offerings must be acquired even if they are free so their terms must be accepted.
                            {% endtrans %}
            </span>
                    </label>
                </div>
            </div>
        {% endblock %}
    {% else %}
        {% block offering_price %}
            <div class="control-group control-small">
                <label class="control-label" for="field-price">{% trans %}Price{% endtrans %}</label>
                <div class="controls ">
                    <input id="field-price" type="text" name="price" value="{{ price }}" placeholder="eg. 0, 28.99, 3.50, 9.00">
                    <span class="info-block info-inline">
            <i class="icon-info-sign fa fa-info-circle"></i>
                        {% trans %}
                            Price in Euros. Leave it in blank to create a <strong>free</strong> offering.
                        {% endtrans %}
          </span>
                </div>
            </div>
        {% endblock %}
    {% endif %}
#}

    {% block form_actions %}
        <div class="form-actions">
            <button class="btn btn-primary" type="submit" name="save">
                {% block save_button_text %}{{ _('Publish Offering') }}{% endblock %}</button>
        </div>
    {% endblock %}
</form>

<div class="modal" tabindex="-1" role="dialog" id="duration-modal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Duration String Wizard</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Please use the wizard to create a valid ISO 8601 Duration string</p>
                <form id="duration-form">
                    <div class="form-group">
                        <label for="yearInput">Year</label>
                        <input name="Y" type="number" min=0 step=0.1 value=0 class="form-control" id="yearInput">
                    </div>
                    <div class="form-group">
                        <label for="monthInput">Month</label>
                        <input name="M" type="number" min=0 step=0.1 value=0 class="form-control" id="monthInput">
                    </div>
                    <div class="form-group">
                        <label for="weekInput">Week</label>
                        <input name="W" type="number" min=0 step=0.1 value=0 class="form-control" id="weekInput">
                    </div>
                    <div class="form-group">
                        <label for="dayInput">Day</label>
                        <input name="D" type="number" min=0 step=0.1 value=0 class="form-control" id="dayInput">
                    </div>
                    <div class="form-group">
                        <label for="hourInput">Hour</label>
                        <input name="H" type="number" min=0 step=0.1 value=0 class="form-control" id="hourInput">
                    </div>
                    <div class="form-group">
                        <label for="minuteInput">Minute</label>
                        <input name="M" type="number" min=0 step=0.1 value=0 class="form-control" id="minuteInput">
                    </div>
                    <div class="form-group">
                        <label for="secondInput">Second</label>
                        <input name="S" type="number" min=0 step=0.1 value=0 class="form-control" id="secondInput">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="copyValue()">Done</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    function copyValue(){
        var duration_string = "P";
        $("#duration-form").serializeArray().map(function(x){
            if (x.value > 0){
                x.value = +x.value;
                duration_string += x.value + x.name;
            }
        });
        if (duration_string == "P") {
            duration_string = "";
        }
        $("#field-DURATION_USAGE_duration").val(duration_string)
        $("#duration-modal").modal('hide');
    }

</script>

<script>
    function enableUsagePolicyOptions(checkboxElem) {
        if (checkboxElem.checked) {
            $("#"+checkboxElem.id).parents().eq(4).children().eq(1).find("input").removeAttr("disabled")
            $("#"+checkboxElem.id).parents().eq(4).children().eq(1).find("select").removeAttr("disabled")
            $("#"+checkboxElem.id).parents().eq(4).children().eq(1).find("button").removeAttr("disabled")
        } else {
            $("#"+checkboxElem.id).parents().eq(4).children().eq(1).find("input").attr("disabled", true)
            $("#"+checkboxElem.id).parents().eq(4).children().eq(1).find("select").attr("disabled", true)
            $("#"+checkboxElem.id).parents().eq(4).children().eq(1).find("button").attr("disabled", true)
        }
    }
</script>