{% extends 'layout.html' %}

{% block title %}{{ document._id|to_string }}{% endblock %}


{% block head %}
  <link href="{{ baseHref }}stylesheets/codemirror.css" rel="stylesheet">
  <script type="text/javascript" src="{{ baseHref }}javascripts/codemirror-compressed.js"></script>

  {% if editorTheme != "default" %}
  <link href="{{ baseHref }}stylesheets/theme/{{ editorTheme }}.css" rel="stylesheet">
  {% endif %}

  <style type="text/css">
    .CodeMirror-scroll {
      height: auto;
      overflow-y: hidden;
      overflow-x: auto;
      width: 100%;
    }
  </style>
{% endblock %}


{% block breadcrumb %}
  <li>
    <a href="">Home</a>
    <span class="divider">/</span>
  </li>
  <li>
    <a href="{{ baseHref }}db/{{ dbName }}">{{ dbName }}</a>
    <span class="divider">/</span>
  </li>
  <li>
    <a href="{{ baseHref }}db/{{ dbName }}/{{ collectionName }}">{{ collectionName }}</a>
    <span class="divider">/</span>
  </li>
  <li class="active">
    {{ document._id|to_string }}
  </li>
{% endblock %}


{% block content %}

<form method="POST" id="documentEditForm" action="{{ baseHref }}db/{{ dbName }}/{{ collectionName }}/{{ document._id | json | safe | url_encode }}">
  {% if !settings.read_only %}
  <input type="hidden" name="_method" value="put">
  <button type="submit" class="btn btn-success btn-large" onclick="return onSubmitClick()">
    <i class="icon-pencil icon-white"></i>
    Save
  </button>
  <br /><br />
  {% endif %}

  <textarea class="span9" id="document" name="document"{% if settings.read_only %} readonly="readonly"{% endif %}>{{ docString }}</textarea>
</form>

<script>
  var doc = CodeMirror.fromTextArea(document.getElementById('document'), {
    mode: { name: "javascript", json: true },
    indentUnit: 4,
    lineNumbers: true,
    autoClearEmptyLines: true,
    matchBrackets: true,
    {% if settings.read_only %}
    readOnly: true,
    {% endif %}
    theme: "{{ editorTheme }}"
  });

  function onSubmitClick() {
    $.ajax({
      type: 'POST',
      url: "{{ baseHref }}checkValid",
      data: {
        document: doc.getValue()
      },
    }).done(function(data) {
      console.log(data);
      if (data === 'Valid') {
        $('#documentInvalidJSON').remove();
        $('#documentEditForm').submit();
      } else if ($('#documentInvalidJSON').length === 0){
        $('#documentEditForm').parent().append('<div id="documentInvalidJSON" class="alert alert-error"><strong>Invalid JSON</strong></div>');
      }
    });
    return false;
  }

</script>

{% endblock %}
