{% extends "layout.html" %}
{% from "_macros.html" import render_co_organizer_select2, render_event_date_defintion_code, render_date_definition_container, render_manage_form_styles, render_manage_form_scripts, render_cropper_header, render_end_container_handling, render_jquery_steps_header, render_cropper_header, render_cropper_code, render_crop_image_form_section, render_radio_buttons, render_field_with_errors, render_field %}

{%- block title -%}
{{ _('Create event') }}
{%- endblock -%}

{% block styles %}
{{ render_manage_form_styles() }}
{% endblock %}

{% block header_before_site_js %}
{{ render_manage_form_scripts() }}
{{ render_jquery_steps_header() }}
{{ render_cropper_header() }}
<script>
$( function() {

  {{ render_cropper_code() }}

  var form = $("#main-form");
  form.validate({
        rules: {
          event_place_id: {
            required: {
              param: true,
              depends: function(element) {
                return $('input[type=radio][name=event_place_choice]:checked').val() == "1";
              }
            }
          },
          "new_event_place-name": {
            required: {
              param: true,
              depends: function(element) {
                return $('input[type=radio][name=event_place_choice]:checked').val() == "2";
              }
            }
          },
          organizer_id: {
            required: {
              param: true,
              depends: function(element) {
                return $('input[type=radio][name=organizer_choice]:checked').val() == "1";
              }
            }
          },
          "new_organizer-name": {
            required: {
              param: true,
              depends: function(element) {
                return $('input[type=radio][name=organizer_choice]:checked').val() == "2";
              }
            }
          }
        }
    });

    {{ render_event_date_defintion_code() }}

  function update_place_container(value) {
    switch (value) {
      case '1':
        $('#existing_place_container').show();
        $('#new_place_container').hide();
        break;
      case '2':
        $('#existing_place_container').hide();
        $('#new_place_container').show();
        break;
    }
  }

  $('#event_place_id').select2({
    width: '100%',
    theme: 'bootstrap4',
    tags: true,
    ajax: {
      url: "{{ url_for('js_autocomplete_place') }}",
      dataType: 'json',
      delay: 250,
      cache: true,
      data: function (params) {
        return {
          keyword: params.term,
          admin_unit_id: '{{ admin_unit.id }}'
        };
      }
    },
    placeholder: "{{ _('Enter place or address') }}",
    createTag: createSelect2Tag,
    insertTag: insertSelect2Tag,
    templateResult: select2TemplateResult
  }).on('select2:close', function (e) {
    var data = select2GetData(e);

    if ("is_new_tag" in data || "gmaps_id" in data) {
      $(this).val(null).trigger('change');
      $('input[type=radio][name=event_place_choice][value=2]').click();
      reset_place_form('new_event_place-');

      if ("is_new_tag" in data) {
        $('#new_event_place-name').val(data.term);
      } else {
        $('#new_event_place-name').val(data.main_text);
        get_gmaps_place_details(data.gmaps_id);
      }

      $('#new_place_container').find(':input').valid();
      $(this).removeClass('is-valid');
    } else {
      $(this).valid();
    }
  });

  function get_gmaps_place_details(place_id) {
    $.ajax({
        url: "{{ url_for('js_autocomplete_gmaps_place') }}",
        type: "get",
        dataType: "json",
        data: "gmaps_id=" + place_id,
        success: function (data) {
          fill_place_form_with_gmaps_place(data, 'new_event_place-');
          $('#new_place_container').find(':input').valid();
        }
    });
  }

  $('input[type=radio][name=event_place_choice]').on('change', function() {
    update_place_container($(this).val());
  });

  $('#new_place_container_search_link').click(function(e){
      e.preventDefault();
      e.stopPropagation();
      reset_place_form('new_event_place-');
      $('input[type=radio][name=event_place_choice][value=1]').click();
  });

  update_place_container($('input[type=radio][name=event_place_choice]:checked').val());

  function update_organizer_container(value) {
    switch (value) {
      case '1':
        $('#existing_organizer_container').show();
        $('#new_organizer_container').hide();
        break;
      case '2':
        $('#existing_organizer_container').hide();
        $('#new_organizer_container').show();
        break;
    }
  }

  $('#organizer_id').select2({
    width: '100%',
    theme: 'bootstrap4',
    tags: true,
    ajax: {
      url: "{{ url_for('api_v1_organization_organizer_list', id=admin_unit.id) }}",
      dataType: 'json',
      delay: 250,
      cache: true,
      data: function (params) {
        return {
          name: params.term,
          per_page: 5
        };
      },
      processResults: function (data) {
        return {
          results: data.items.map(p => ({"id": p.id, "text": p.name}))
        };
      }
    },
    placeholder: "{{ _('Enter organizer') }}",
    createTag: createSelect2Tag,
    insertTag: insertSelect2Tag,
    templateResult: select2TemplateResult
  }).on('select2:close', function (e) {
    var data = select2GetData(e);

    if ("is_new_tag" in data) {
      $(this).val(null).trigger('change');
      $('input[type=radio][name=organizer_choice][value=2]').click();
      reset_organizer_form('new_organizer-');

      $('#new_organizer-name').val(data.term);

      $('#new_organizer_container').find(':input').valid();
      $(this).removeClass('is-valid');
    } else {
      $(this).valid();
    }
  });

  $('input[type=radio][name=organizer_choice]').on('change', function() {
    update_organizer_container($(this).val());
  });

  $('#organizer_id').on('select2:select', function (e) {
      $(this).valid();
  });

  $('#new_organizer_container_search_link').click(function(e){
      e.preventDefault();
      e.stopPropagation();
      reset_organizer_form('new_organizer-');
      $('input[type=radio][name=organizer_choice][value=1]').click();
  });

  update_organizer_container($('input[type=radio][name=organizer_choice]:checked').val());

  {{ render_co_organizer_select2(admin_unit.id) }}

});
</script>
{% endblock %}
{% block content %}

<h1>{{ _('Create event') }}</h1>

{{ render_date_definition_container(form.date_definition_template, "date-definition-template d-none") }}

<form id="main-form" action="" method="POST" enctype="multipart/form-data">
  {{ form.hidden_tag() }}

  <div class="card mb-4">
    <div class="card-header">
      {{ _('Event') }}
    </div>
    <div class="card-body">
      {{ render_field_with_errors(form.name) }}
      {{ render_field_with_errors(form.description, style="min-height:10rem;") }}
    </div>
  </div>

  <div class="card mb-4">
    <div class="card-header">
      {{ _('Event dates') }}
    </div>
    <div class="card-body pb-3">
      {% for date_definition in form.date_definitions %}
        {{ render_date_definition_container(date_definition) }}
      {% endfor %}

      <button type="button" class="btn btn-outline-secondary btn-small" id="add-date-defintion-btn"><i class="fa fa-calendar-plus"></i> {{ _('Add event date') }}</button>
    </div>
  </div>

  <div class="card mb-4">
    <div class="card-header">
      {{ _('Organizer') }} *
    </div>
    <div class="card-body">
      <div>
        <div class="form-text mt-0 text-muted w-100">{{ _("Select the organizer. If the organizer is not yet on the list, just enter it.") }}</div>
        <div style="display: none;">{{ render_radio_buttons(form.organizer_choice) }}</div>
      </div>

      <div class="my-2" id="existing_organizer_container">
        {{ render_field_with_errors(form.organizer_id, class="w-100", label_hidden=True) }}
      </div>

      <div class="my-2" id="new_organizer_container">
        {{ form.new_organizer.hidden_tag() }}
        {{ render_field_with_errors(form.new_organizer.form.name, is_required=True) }}
        {{ form.new_organizer.form.location.hidden_tag() }}
        {{ render_field_with_errors(form.new_organizer.form.location.street) }}
        {{ render_field_with_errors(form.new_organizer.form.location.postalCode) }}
        {{ render_field_with_errors(form.new_organizer.form.location.city) }}

        <div class="my-4">
          <a href="#" id="new_organizer_container_search_link"><i class="fa fa-search"></i> {{ _('Switch to organizer search') }}</a>
        </div>
      </div>

      {{ render_field_with_errors(form.co_organizer_ids, class="w-100") }}
    </div>
  </div>

  <div class="card mb-4">
    <div class="card-header">
      {{ _('Place') }} *
    </div>
    <div class="card-body">

      <div>
        <div class="form-text mt-0 text-muted w-100">{{ _("Choose where the event takes place. If the venue is not yet in the list, just enter it.") }}</div>
        <div style="display: none;">{{ render_radio_buttons(form.event_place_choice) }}</div>
      </div>

      <div class="my-2" id="existing_place_container">
        {{ render_field_with_errors(form.event_place_id, class="w-100", label_hidden=True) }}
      </div>

      <div class="my-2" id="new_place_container">
        {{ form.new_event_place.hidden_tag() }}
        {{ render_field_with_errors(form.new_event_place.form.name, is_required=True) }}
        {{ form.new_event_place.form.location.hidden_tag() }}
        {{ render_field_with_errors(form.new_event_place.form.location.street) }}
        {{ render_field_with_errors(form.new_event_place.form.location.postalCode) }}
        {{ render_field_with_errors(form.new_event_place.form.location.city) }}
        {{ render_field_with_errors(form.new_event_place.form.location.state) }}
        {{ render_field_with_errors(form.new_event_place.form.location.latitude) }}
        {{ render_field_with_errors(form.new_event_place.form.location.longitude) }}

        <div class="my-4">
          <a href="#" id="new_place_container_search_link"><i class="fa fa-search"></i> {{ _('Switch to place search') }}</a>
        </div>
      </div>

    </div>
  </div>

  {{ render_crop_image_form_section(form.photo) }}

  <div class="card mb-4">
    <div class="card-header">
      {{ _('Access') }}
    </div>
    <div class="card-body">
      {{ render_field_with_errors(form.accessible_for_free, ri="switch") }}
      {{ render_field_with_errors(form.registration_required, ri="switch") }}
      {{ render_field_with_errors(form.price_info) }}
      {{ render_field_with_errors(form.ticket_link) }}
      {{ render_field_with_errors(form.booked_up, ri="switch") }}
      {{ render_field_with_errors(form.attendance_mode, class="autocomplete w-100") }}
    </div>
  </div>

  <div class="card mb-4">
    <div class="card-header">
      {{ _('Target group') }}
    </div>
    <div class="card-body">
      {{ render_field_with_errors(form.target_group_origin, class="autocomplete w-100") }}
      {{ render_field_with_errors(form.kid_friendly, ri="switch") }}
      {{ render_field_with_errors(form.age_from) }}
      {{ render_field_with_errors(form.age_to) }}
      {{ render_field_with_errors(form.expected_participants) }}
    </div>
  </div>

  <div class="card mb-4">
    <div class="card-header">
      {{ _('Additional information') }}
    </div>
    <div class="card-body">
      {{ render_field_with_errors(form.category_ids, class="autocomplete-multi w-100") }}
      {{ render_field_with_errors(form.tags) }}
      {{ render_field_with_errors(form.external_link) }}
    </div>
  </div>

  {% if form.rating.choices|length > 1 %}
  <div class="card mb-4">
    <div class="card-header">
      {{ _('Rating') }}
    </div>
    <div class="card-body">
      {{ render_field_with_errors(form.rating) }}
    </div>
  </div>
  {% endif %}

  <div class="d-flex flex-column flex-sm-row">
    {{ form.submit(class="btn btn-primary m-1")|safe }}
    {{ form.submit_draft(class="btn btn-secondary m-1")|safe }}
  </div>

</form>

{% endblock %}
