{% extends "base.html" %}
{% block content %}

{% set search_enabled = config['SEARCH_CONF']['enabled'] %}
{% if search_enabled %}
    <input type="text" id="searchBar" placeholder="Search">
    <ul id="searchHits"></ul>
{% endif %}

<div id="files">

    {% if not view_only %}
        <div class="d-flex" id="main-links">
            <div style="width: 100%;" class="d-flex">
                <a class="btn" href="/notes/new?path={{current_path}}">
                    New Note
                    <svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M0 3.75C0 2.784.784 2 1.75 2h12.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0114.25 14H1.75A1.75 1.75 0 010 12.25v-8.5zm1.75-.25a.25.25 0 00-.25.25v8.5c0 .138.112.25.25.25h12.5a.25.25 0 00.25-.25v-8.5a.25.25 0 00-.25-.25H1.75zM3.5 6.25a.75.75 0 01.75-.75h7a.75.75 0 010 1.5h-7a.75.75 0 01-.75-.75zm.75 2.25a.75.75 0 000 1.5h4a.75.75 0 000-1.5h-4z"></path></svg>
                </a>
                <a class="btn" href="/bookmarks/new?path={{current_path}}">
                    New Bookmark
                    <svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M4.75 2.5a.25.25 0 00-.25.25v9.91l3.023-2.489a.75.75 0 01.954 0l3.023 2.49V2.75a.25.25 0 00-.25-.25h-6.5zM3 2.75C3 1.784 3.784 1 4.75 1h6.5c.966 0 1.75.784 1.75 1.75v11.5a.75.75 0 01-1.227.579L8 11.722l-3.773 3.107A.75.75 0 013 14.25V2.75z"></path></svg>
                </a>
                <form action="/folders/delete" method="post" onsubmit="return confirm('Delete this folder and its items permanently?')" style="margin: 0px;">
                    {{ delete_form.csrf_token }}
                    {{ delete_form.dir_name(value=current_path) }}
                    <button class="btn btn-delete">
                        Delete folder
                    <svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M6.5 1.75a.25.25 0 01.25-.25h2.5a.25.25 0 01.25.25V3h-3V1.75zm4.5 0V3h2.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75zM4.496 6.675a.75.75 0 10-1.492.15l.66 6.6A1.75 1.75 0 005.405 15h5.19c.9 0 1.652-.681 1.741-1.576l.66-6.6a.75.75 0 00-1.492-.149l-.66 6.6a.25.25 0 01-.249.225h-5.19a.25.25 0 01-.249-.225l-.66-6.6z"></path></svg>
                    </button>
                </form>
            </div>
            <div class="d-flex">
                <form action="/folders/create" method="post" class="d-flex">
                    {{ new_folder_form.csrf_token }}
                    {{ new_folder_form.parent_dir(value=current_path) }}
                    {{ new_folder_form.new_dir(placeholder="New folder name") }}
                    {{ new_folder_form.submit() }}
                </form>
                {% if current_path != "" %}
                    <form action="/folders/rename" method="post" class="d-flex">
                        {{ rename_form.csrf_token }}
                        {{ rename_form.current_path(value=current_path) }}
                        {{ rename_form.new_name(placeholder="Name") }}
                        {{ rename_form.submit() }}
                    </form>
                {% endif %}
            </div>
        </div>
    {% endif %}

	<h3>Recently modified</h3>
	<ul>
      {% for d in most_recent %}
        <li style="display: flex; justify-content: space-between"><a href="/dataobj/{{ d['id'] }}">{{ d['title'] }}</a><p style="color: #696969; margin: 0">Modified at {{ d['modified_at'] }}</p></li>
      {% endfor %}
	</ul>
    <ul>
        
        <div class="folder-tags">
            {% for tag in tag_cloud %}
            <a href="/tags/{{ tag }}">
                <span class="post-tag">{{ tag }}</span>
            </a>
            {% endfor %}
        </div>

        {% for subdir in dir.child_dirs.values() | sort(attribute="name") %}
            <li class="dir">
                <svg class="octicon ml-2 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.75 1A1.75 1.75 0 000 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0016 13.25v-8.5A1.75 1.75 0 0014.25 3h-6.5a.25.25 0 01-.2-.1l-.9-1.2c-.33-.44-.85-.7-1.4-.7h-3.5z"></path></svg>
                <a href="/?path={{current_path}}{{subdir.name}}/">{{ subdir.name }}</a>
            </li>
        {% endfor %}
        {% for file in dir.child_files | sort(attribute="title") %}
            <li class="file">
                <svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.06zM2 1.75C2 .784 2.784 0 3.75 0h5.086c.464 0 .909.184 1.237.513l3.414 3.414c.329.328.513.773.513 1.237v8.086A1.75 1.75 0 0112.25 15h-8.5A1.75 1.75 0 012 13.25V1.75z"></path></svg>
                <a href="/dataobj/{{file.id}}">{{ file.title }}</a>
            </li>
        {% endfor %}
    </ul>
</div>

{% if search_enabled %}
    {% include "markdown-parser.html" %}
{% endif %}
<script>
  // search functionality
  {% if search_enabled %}  
    function sanitize_match_html(rendered, q)
    {
      let stripped_tags = new RegExp("(?:<img.*>|<mark>|</mark>|<bold>|<bold>)", "ig"); // remove unnecessary tags
      let replace_headings = new RegExp("<h[0-9][^>]*>(.*)</h[0-9]>", "ig"); // replace headings with <p>
      let highlight_regex = new RegExp(`(?![^<>]*>)(${q})`, "ig"); // replace query in html text, not attributes, with highlights
      let output = rendered.replace(stripped_tags, "").replace(replace_headings, "<p>$1</p>").replace(highlight_regex, "<mark>$1</mark>");
      if (!output.match("(?![^<>]*>)\\w+")) { output = ""; } // check there is actual text, not html, in the output
      return output;
    }
    function appendHit(hit, q) {
      let hitsDiv = document.getElementById("searchHits");
      let hitLi = document.createElement("li");
      let a = document.createElement("a");
      a.href = `/dataobj/${hit["id"]}`, a.textContent = hit["title"];
      hitLi.append(a);
      let body = document.createElement("div");
      if ("matches" in hit)
      {
        let max_matches = 4, rendered_matches = "<p>Matches:</p>", n_rendered_matches = 0;
        hit["matches"].every((match) => {
          let curr_match_output = sanitize_match_html(window.parser.customRender(match), q);
          if (curr_match_output != "") { // only render if there is text remaining after sanitization
            rendered_matches += "<hr>" + curr_match_output;
            n_rendered_matches++;
          }
          if (n_rendered_matches == max_matches) {
            rendered_matches += "...";
            return false; // stop looping
          }
          return true; // keep going
        })
        body.innerHTML += rendered_matches;
      }
      hitLi.append(body);
      hitsDiv.appendChild(hitLi);
    }

    let input = document.getElementById("searchBar");
    input.addEventListener('input', async function(e) {
      let query = input.value;
      if (input.value !== "")
      {
        let searchQuery = await fetch(`${SCRIPT_ROOT}/search?query=${encodeURIComponent(input.value)}`, {
          "method": "GET"
        });
        if (searchQuery.ok && query == input.value) {  
          let data = await searchQuery.json(), i = 0;
          document.getElementById("searchHits").innerHTML = "";
          data.forEach(function(hit)
          {
            if (query !== input.value) return;
            appendHit(hit, query);
          })
    
        }
      }
      else {
        document.getElementById("searchHits").innerHTML = "";
      }
    });
  {% endif %}
</script>
{% endblock %}
