{% extends "post_editor_base.html" %}

{% block render_block %}
<hr class="row col-md-12" style="border-top:1px solid #9ca299; margin-left: 15px; width: 93%">
<div class="row col-md-12">
  <div class="col-md-1 group-by-header">
    <h5> View:</h5>
  </div>
  <div class="col-md-5">
    <span class="group-by-options">
    <div class="radio-inline radio-cluster">
      <label>
        <input type="radio" name="cluster-radio" id="markdown-only">Text Editor Only
      </label>
    </div>
    <div class="radio-inline radio-cluster">
      <label>
        <input type="radio" name="cluster-radio" id="split-view" checked='checked'> Split View
      </label>
    </div>
    <div class="radio-inline radio-cluster">
      <label>
        <input type="radio" name="cluster-radio" id="rendered-only">Rendered Only
      </label>
    </div>
  </span>
  </div>
</div>
<div class="row row-space-3"></div>

<div class="row">
  <div class="col-md-12">
    <a class="col-md-3" target="_blank" rel="noopener noreferrer" href="https://daringfireball.net/projects/markdown/basics" style="padding-right: 13px">
     How to write Markdown
     <i class="glyphicon glyphicon-new-window"></i>
   </a>
  </div>
</div>
<div class="row row-space-2"></div>
<div class="row">
  <div class="col-md-12">
    <div class="col-md-6" id="post_text_div">
      <textarea class="input input-resize-both form-control" id="post_text" type="text" placeholder="Start writing markdown here" style="height:100%; width:100%">{{markdown if markdown}}
      </textarea>
    </div>
    <div class="col-md-6" id="rendered-markdown">
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}

{{ super() }}

<script>
  $("#markdown-only").on("click", function() {
    var md_text = $("#post_text_div")[0];
    var rendered_text = $("#rendered-markdown")[0];
    md_text.className = "col-md-12"
    md_text.style.visibility = "visible"
    rendered_text.style.visibility = "hidden";
    rendered_text.style.display = "none";
  })

  $("#split-view").on("click", function() {
    var md_text = $("#post_text_div")[0];
    var rendered_text = $("#rendered-markdown")[0];
    md_text.className = "col-md-6";
    md_text.style.visibility = "visible";
    md_text.style.display = "inherit";
    rendered_text.className = "col-md-6";
    rendered_text.style.visibility = "visible";
    rendered_text.style.display = "inherit";
  });

  $("#rendered-only").on("click", function() {
    var md_text = $("#post_text_div")[0];
    var rendered_text = $("#rendered-markdown")[0];
    md_text.style.visibility = "hidden";
    md_text.style.display = "none";
    rendered_text.className = "col-md-12";
    rendered_text.style.visibility = "visible";
    rendered_text.style.display = "inherit";
  })

  function refreshRenderedMarkdown() {
    var markdownString = $('#post_text').val();

    var metadata_ids = ['#post_title', '#post_author', '#post_created_at',
      '#post_updated_at', '#post_tags', '#post_tldr'
    ]
    var metadata_vals = {}
    $.each(metadata_ids, function(i, mid) {
      metadata_key = mid.split("_")[1];
      textfield = $(mid)[0].value;
      metadata_vals[metadata_key] = textfield;
    });

    // authors and tags are a little bit different
    tags = $("#post_tags").select2().val()
    if (tags !== null) {
      metadata_vals['tags'] = tags.join(", ")
    } else {
      metadata_vals['tags'] = ''
    }

    author = $("#post_author").select2().val()
    if (author !== null) {
      metadata_vals['author'] = author.join(", ")
    } else {
      metadata_vals['author'] = ''
    }

    metadata_content =
      "<h1>" + metadata_vals['title'] + "</h1>" +
      "<p><strong>Author</strong>: " + metadata_vals['author'] + "<br/>" +
      "<strong>Date Created</strong>: " + metadata_vals['created'] + "<br/>" +
      "<strong>Date Updated</strong>: " + metadata_vals['updated'] + "<br/>" +
      "<strong>Tags</strong>: " + metadata_vals['tags'] + "<br/>" +
      "<strong>TLDR</strong>: " + metadata_vals['tldr'] + "<br/> </p>"

    //escape underscores in equations
    var blocks = markdownString.split('```')
    markdownString = metadata_content
    for (var i = 0; i < blocks.length; i++) {
      if (i % 2 == 1) {
        var block = blocks[i]
        markdownString += block + '```'
      } else {
        var block = blocks[i]
        block = escapeEquationBlocks(block, '$$')
        block = escapeEquationBlocks(block, '$')
        markdownString += block
        if (i != blocks.length - 1) {
          markdownString += '```'
        }
      }
    }

    // Using async version of marked
    marked(markdownString, function(err, content) {
      if (err) throw err;
      //make sure images are not larger than the page
      content = content.split('<img ').join('<img style="max-width:100%"')
        //make tables look prettier:
      content = content.split('<table>').join('<table class="table table-striped table-condensed table-bordered">')
      content = content.split('<table class="dataframe">').join('<table class="table table-striped table-condensed table-bordered">')
      $('#rendered-markdown').html(content)
    });

    try {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    } catch (e) {
      //console.log(e);
    }
  }

  var timeout = null;
  $("#post_text").on("input", function(e) {
    if ($(this).data("lastval") != $(this).val()) {
      $(this).data("lastval", $(this).val());


      if (timeout !== null) {
        clearTimeout(timeout);
      }
      //if no new input is entered within 1 second, apply the filters
      timeout = setTimeout(function() {
        refreshRenderedMarkdown();
      }, 500);
    };
  });

  var metadata_fields = ['#post_title', '#post_author', '#post_created_at',
    '#post_updated_at', '#post_tags', '#post_tldr'
  ]

  $.each(metadata_fields, function(i, field) {
    var timeout = null;
    if (field != "#post_tags") {
      $(field).on("input", function(e) {
        if ($(this).data("lastval") != $(this).val()) {
          $(this).data("lastval", $(this).val());

          if (timeout !== null) {
            clearTimeout(timeout);
          }
          //if no new input is entered within 1 second, apply the filters
          timeout = setTimeout(function() {
            refreshRenderedMarkdown();
          }, 500);
        };
      });
    }
  })

  $(document).ready(function() {
    marked.setOptions({
      highlight: function(code, lang) {
        try {
          return hljs.highlight(lang, code, true).value;
        } catch (err) {
          console.log(err)
          try {
            return hljs.highlightAuto(code).value;
          } catch (err) {
            return code;
          }
        }
      },
      renderer: new marked.Renderer(),
      gfm: true,
      toc: true,
      tables: true,
      breaks: true,
      pedantic: false,
      sanitize: false,
      smartLists: true,
      smartypants: true
    });
    var hash = window.location.hash;
    if (hash) {
      var text = decodeURIComponent(hash)
      text = text.replace("#", '')
    }
    var text = $("#post_text").text()
    var len = text.split(/\r\n|\r|\n/).length
    $("#post_text").text(text)
    refreshRenderedMarkdown();
  });

</script>
{% endblock scripts %}
