{% extends "base.html" %}

{% block title %}Instrument — {{ service_name }}{% endblock %}

{% block stylesheets %}
  {{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-select.min.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-toggle.min.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/inscrybmde.min.css') }}" />
{% endblock %}

{% block scripts %}
  {{ super() }}
  <script src="{{ url_for('static', filename='js/bootstrap-select.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/bootstrap-toggle.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/inscrybmde.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/markdown_image_upload.js') }}"></script>
  <script>
  window.categories = [
    {% for category in instrument_log_categories %}
      {
        'id': '{{ category.id }}',
        'title': '{{ category.title }}',
        'theme': '{{ category.theme.name.lower() }}'
      },
    {% endfor %}
  ];
  window.new_category_counter = -1;
  $(function() {
    $('[data-toggle="tooltip"]').tooltip();
    function updateCategoryJSON() {
      var category_json = JSON.stringify(window.categories);
      $('#input-categories').val(category_json);
    }
    updateCategoryJSON();
    function updateEventHandler() {
      $('[data-category-id][data-category-id!=""]').each(function() {
        $(this).find('input').on('change', function() {
          var category_element = $(this).closest('[data-category-id]');
          var category_id = category_element.attr('data-category-id');
          var category_title = category_element.find('input[type="text"]').val().trim();
          if (category_title === "") {
            category_element.parent().addClass('has-error').find('.help-block').html("Please enter a category title.");
          } else if (category_title.length > 100) {
            category_element.parent().addClass('has-error').find('.help-block').html("Please enter a shorter category title (at most 100 characters).");
          } else {
            category_element.parent().removeClass('has-error').find('.help-block').html("");
          }
          window.categories.forEach(function(category) {
            if (category.id === category_id) {
              category.title = category_title;
            }
          });
          updateCategoryJSON();
        }).change();
        $(this).find('select').on('change', function() {
          var category_element = $(this).closest('[data-category-id]');
          var category_id = category_element.attr('data-category-id');
          var category_theme = category_element.find('option:selected').val();
          window.categories.forEach(function(category) {
            if (category.id === category_id) {
              category.theme = category_theme;
            }
          });
          updateCategoryJSON();
        });
        $(this).find('.button-delete-category').on('click', function() {
          var category_element = $(this).closest('[data-category-id]');
          var category_id = category_element.attr('data-category-id');
          category_element.parent().remove();
          window.categories = window.categories.filter(function(category) {
            return category.id !== category_id;
          });
          updateCategoryJSON();
        });
      });
    }
    $('#button-instrument-log-new-category').on('click', function () {
      $($('#instrument-log-category-template').html()).insertBefore($(this).parent());
      $(this).parent().prev('.form-group').find('.input-group').attr('data-category-id', window.new_category_counter);
      window.categories.push({
        'id': window.new_category_counter.toString(),
        'title': '',
        'theme': '{{ instrument_log_category_themes[0].name.lower() }}'
      });
      window.new_category_counter -= 1;
      $('[data-category-id][data-category-id!=""] select').addClass('selectpicker');
      $('.selectpicker').selectpicker();
      updateEventHandler();
      updateCategoryJSON();
    });
    updateEventHandler();
    $('form').on('submit', function() {
      console.log($(this).find('.has-error'));
      return $(this).find('.has-error').length === 0;
    })

    function updateDescriptionMarkdown() {
      if ($('#input-markdown').prop('checked')) {
        window.mde_descrption = new InscrybMDE({
          element: $("#input-description")[0],
          indentWithTabs: false,
          spellChecker: false,
          status: false,
          hideIcons: ["guide", "fullscreen", "side-by-side", "quote"],
          showIcons: ["code", "table"],
          minHeight: '300px',
        });
        setupImageDragAndDrop(window.mde_descrption);
      } else {
        if (window.mde_descrption) {
          window.mde_descrption.toTextArea();
          window.mde_descrption = null;
        }
      }
    }
    $('#input-markdown').change(updateDescriptionMarkdown);
    updateDescriptionMarkdown();

    function updateNotesMarkdown() {
      if ($('#input-notes-are-markdown').prop('checked')) {
        window.mde_notes = new InscrybMDE({
          element: $("#input-notes")[0],
          indentWithTabs: false,
          spellChecker: false,
          status: false,
          hideIcons: ["guide", "fullscreen", "side-by-side", "quote"],
          showIcons: ["code", "table"],
          minHeight: '300px',
        });
        setupImageDragAndDrop(window.mde_notes);
      } else {
        if (window.mde_notes) {
          window.mde_notes.toTextArea();
          window.mde_notes = null;
        }
      }
    }
    $('#input-notes-are-markdown').change(updateNotesMarkdown);
    updateNotesMarkdown();
  });
  </script>
{% endblock %}

{% block content %}
  <form method="post">
  {{ instrument_form.hidden_tag() }}
    <div class="col-md-12">
      <div class="form-group {% if instrument_form.name.name in instrument_form.errors %}has-error{% endif %}">
        <label for="input-name" class="control-label">Name</label>
         <input type="text" class="form-control" id="input-name" placeholder="Name" name="{{ instrument_form.name.name }}" value="{{ instrument_form.name.data or instrument_form.name.default or '' }}">
      </div>
      <div class="form-group {% if instrument_form.description.name in instrument_form.errors %}has-error{% endif %}" style="min-height: 395px;">
        <label for="input-description" class="control-label">Description</label>
        <label for="input-markdown" style="font-weight:400" class="pull-right">
          <input type="checkbox" id="input-markdown" name="{{ instrument_form.is_markdown.name }}" {% if instrument_form.is_markdown.data %}checked="checked"{% endif %}> Use Markdown
        </label>
        <textarea class="form-control" style="resize: vertical; min-height: 371px" id="input-description" name="{{ instrument_form.description.name }}" placeholder="Description">{{ instrument_form.description.data or instrument_form.description.default or '' }}</textarea>
      </div>
      <div class="form-group {% if instrument_form.notes.name in instrument_form.errors %}has-error{% endif %}" style="min-height: 395px;">
        <label for="input-notes" class="control-label">Instrument Scientist Notes</label>
        <label for="input-notes-are-markdown" style="font-weight:400" class="pull-right">
          <input type="checkbox" id="input-notes-are-markdown" name="{{ instrument_form.notes_are_markdown.name }}" {% if instrument_form.notes_are_markdown.data %}checked="checked"{% endif %}> Use Markdown syntax for Notes
        </label>
        <textarea class="form-control" style="resize: vertical; min-height: 371px" id="input-notes" name="{{ instrument_form.notes.name }}" placeholder="Instrument Scientist Notes">{{ instrument_form.notes.data or instrument_form.notes.default or '' }}</textarea>
      </div>
      <div class="form-group">
        <label for="input-instrument_repsonsible_users" class="control-label">Instrument Scientists</label>
        <select name="{{ instrument_form.instrument_responsible_users.name }}" class="selectpicker form-control" multiple="multiple" data-live-search="true">
          {% for choice in instrument_form.instrument_responsible_users.choices %}
              <option value="{{ choice[0] }}" {% if (instrument_form.instrument_responsible_users.data and choice[0] in instrument_form.instrument_responsible_users.data) or (not instrument_form.instrument_responsible_users.data and instrument_form.instrument_responsible_users.default and choice[0] in instrument_form.instrument_responsible_users.default) %}selected="selected"{% endif %}>{{ choice[1] }} (#{{ choice[0] }})</option>
          {% endfor %}
        </select>
      </div>
      <label>Instrument Log Categories</label>
      <div class="hidden" id="instrument-log-category-template">
        <div class="form-group">
          <div class="input-group" data-category-id="">
            <input type="text" class="form-control" placeholder="Category Name">
            <select data-style="btn-default instrument-log-category-theme-btn" data-width="20em">
              {% for theme in instrument_log_category_themes %}
              <option {% if loop.index == 1 %}selected="selected"{% endif %} value="{{ theme.name.lower() }}">{{ theme.name.title() }}</option>
              {% endfor %}
            </select>
            <span class="input-group-btn">
              <button class="btn btn-danger button-delete-category" type="button"><i class="fa fa-trash"></i></button>
            </span>
          </div>
          <span class="help-block"></span>
        </div>
      </div>
      {% for category in instrument_log_categories %}
      <div class="form-group">
        <div class="input-group" data-category-id="{{ category.id }}">
          <input type="text" class="form-control" placeholder="Category Name" value="{{ category.title }}">
          <select class="selectpicker" data-style="btn-default instrument-log-category-theme-btn" data-width="20em">
            {% for theme in instrument_log_category_themes %}
            <option {% if category.theme == theme %}selected="selected"{% endif %} value="{{ theme.name.lower() }}">{{ theme.name.title() }}</option>
            {% endfor %}
          </select>
          <span class="input-group-btn">
            <button class="btn btn-danger button-delete-category" type="button"><i class="fa fa-trash"></i></button>
          </span>
        </div>
        <span class="help-block"></span>
      </div>
      {% endfor %}
      <div></div>
      <div class="form-group text-right">
        <button class="btn btn-success" type="button" id="button-instrument-log-new-category"><i class="fa fa-plus"></i></button>
      </div>
      <input type="hidden" id="input-categories" name="{{ instrument_form.categories.name }}" value="">
      <div class="checkbox">
        <label for="input-users_can_create_log_entries">
          <input type="checkbox" id="input-users_can_create_log_entries" name="{{ instrument_form.users_can_create_log_entries.name }}" {% if instrument_form.users_can_create_log_entries.data %}checked="checked"{% endif %}> Users can create log entries
        </label>
      </div>
      <div class="checkbox">
        <label for="input-users_can_view_log_entries">
          <input type="checkbox" id="input-users_can_view_log_entries" name="{{ instrument_form.users_can_view_log_entries.name }}" {% if instrument_form.users_can_view_log_entries.data %}checked="checked"{% endif %}> Users can view log entries
        </label>
      </div>
      <div class="checkbox">
        <label for="input-create_log_entry_default">
          <input type="checkbox" id="input-create_log_entry_default" name="{{ instrument_form.create_log_entry_default.name }}" {% if instrument_form.create_log_entry_default.data %}checked="checked"{% endif %}> Create log entries for objects created by instrument scientists <i class="fa fa-question-circle" data-toggle="tooltip" data-placement="top" title="This sets the default for whether or not an instrument log entry should be created or not. The user can manually toggle the checkbox during object creation to override this default."></i>
        </label>
      </div>
      <div class="checkbox">
        <label for="input-is_hidden">
          <input type="checkbox" id="input-is_hidden" name="{{ instrument_form.is_hidden.name }}" {% if instrument_form.is_hidden.data %}checked="checked"{% endif %}> Hide this instrument from instrument lists
        </label>
      </div>
    </div>
    <div class="form-group row clearfix" style="padding-right:0.75em">
      <div class="col-md-3 col-md-offset-6">
        <a href="{{ url_for('.instruments') }}" class="btn btn-default pull-right" style="width:20em">Cancel</a>
      </div>
      <div class="col-md-3">
        <button type="submit" name="action_submit" class="btn btn-primary pull-right" style="width:20em">{{ submit_text }}</button>
      </div>
    </div>
  </form>
{% endblock %}
