{% extends "layout.html" %}
{% set current_page = "search" %}

{% set title = "OD-Database - Search" %}

{% block body %}
    <div class="container">

        <div class="card">
            <div class="card-header">Search</div>
            <div class="card-body">
                <form action="/search" id="sfrm">

                    <div class="form-row">

                        {# Query #}
                        <div class="input-group form-group">
                            <div class="input-group-prepend">
                                <div class="input-group-text">
                                    <label for="matchAll" style="margin-bottom: 0">Match any word&nbsp</label>
                                    <input title="Toggle between 'match all words' and 'match any word'" type="checkbox"
                                           id="matchAll" name="all" {{ "checked" if match_all }}>
                                </div>
                            </div>
                            <input class="form-control" name="q" id="q" placeholder="Query" value="{{ q }}">
                            <input type="hidden" name="p" id="page" value="{{ p }}">
                        </div>
                    </div>
                    {# Size #}
                    <div class="text-muted" style="text-align: center">File size</div>
                    <input title="File size" id="sizeSlider">
                    <input type="hidden" name="size_min" id="sizeMin" value="{{ size_min }}">
                    <input type="hidden" name="size_max" id="sizeMax" value="{{ size_max }}">
                    {# Date #}
                    <div class="text-muted" style="text-align: center">File date</div>
                    <input title="File date" id="dateSlider">
                    <input type="hidden" name="date_min" id="dateMin" value="{{ date_min }}">
                    <input type="hidden" name="date_max" id="dateMax" value="{{ date_max }}">

                    <div class="form-row">
                        {# File extension #}
                        <div class="form-group col-md-6">
                            <div class="text-muted">File extension</div>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <div class="input-group-text">.</div>
                                </div>
                                <input name="ext" placeholder="Extensions, comma-separated" class="form-control"
                                       value="{{ extensions }}">
                            </div>
                        </div>
                        {# Fields #}
                        <div class="col-md-5" style="margin-left: 1em">
                            <div class="text-muted">Search in</div>
                            <div class="form-group form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" id="field_name"
                                       name="field_name"{{ "checked" if field_name else "" }}>
                                <label class="form-check-label" for="field_name">name</label>
                            </div>
                            <div class="form-group form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" id="field_trigram"
                                       name="field_trigram"{{ "checked" if field_trigram else "" }}>
                                <label class="form-check-label" for="field_trigram">name.trigram</label>
                            </div>
                            <div class="form-group form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" id="field_path"
                                       name="field_path" {{ "checked" if field_path else "" }}>
                                <label class="form-check-label" for="field_path">path</label>
                            </div>
                        </div>
                    </div>

                    <div class="text-muted">Display options</div>
                    <div class="form-row">

                        <div class="form-group col-md-3">
                            {# Sort order #}
                            <select class="form-control" name="sort_order" title="Sort order">
                                <option disabled>Sort order</option>
                                <option value="score" {{ "selected" if sort_order == "score" else "" }}>Relevance
                                </option>
                                <option value="size_asc" {{ "selected" if sort_order == "size_asc" else "" }}>Size
                                    ascending
                                </option>
                                <option value="size_dsc" {{ "selected" if sort_order == "size_dsc" else "" }}>Size
                                    descending
                                </option>
                                <option value="date_asc" {{ "selected" if sort_order == "date_asc" else "" }}>Date
                                    ascending
                                </option>
                                <option value="date_dsc" {{ "selected" if sort_order == "date_dsc" else "" }}>Date
                                    descending
                                </option>
                                <option value="none" {{ "selected" if sort_order == "none" else "" }}>No order
                                    (faster)
                                </option>
                            </select>
                        </div>
                        {# Results per page #}
                        <div class="form-group col-md-2">
                            <select class="form-control" name="per_page" title="Results per page">
                                <option disabled>Results per page</option>
                                {% for results in results_set %}
                                    <option{{ " selected" if per_page == results }}>{{ results }}</option>
                                {% endfor %}
                            </select>
                        </div>


                        {# Search button #}
                        <div class="form-group col-md-7">

                            <input id="s" class="btn btn-primary btn-shadow" type="submit" value="Search"
                                   style="float: right">
                        </div>
                    </div>
                    {% if show_captcha %}
                        {{ captcha.get_code()|safe }}
                    {% endif %}

                </form>
            </div>
        </div>

        {% if results and results["hits"]["total"] > 0 %}
            <div class="card">
                <div class="card-body">

                    <span class="text-muted">{{ results["hits"]["total"] }} result(s) in {{ results["took"] }}ms</span>

                    <div class="table-responsive">
                        <table class="table">
                            <tbody>

                            {% for hit in results["hits"]["hits"] %}
                                {% set src = hit["_source"] %}
                                {% if "name" in hit["highlight"] %}
                                    {% set hl_name = hit["highlight"]["name"][0] %}
                                {% elif "name.nGram" in hit["highlight"] %}
                                    {% set hl_name = hit["highlight"]["name.nGram"][0] %}
                                {% else %}
                                    {% set hl_name = src["name"] %}
                                {% endif %}

                                {% set hl_path = hit["highlight"]["path"][0] if "path" in hit["highlight"] else src["path"] %}

                                <tr>
                                    <td>
                                        {% set category = get_mime(src["ext"]) %}
                                        {% set url = src["website_url"] + src["path"] + "/" + src["name"] + ("." if src["ext"] != "" else "") + src["ext"] %}
                                        {# Preview #}
                                        {% if category == "image" %}
                                            <i class="fas fa-eye prev-icon" data-toggle="popover" tabindex="-1"
                                               data-content='<img class="prev-img" src="{{ url }}">'></i>
                                        {% endif %}
                                        {# File name & link #}
                                        <a href="{{ url }}"><span>{{ hl_name |safe }}{{ ("." if src["ext"] != "" else "") + src["ext"] }}</span></a>
                                        {# File type badge #}
                                        {% if category %}
                                            <span class="badge badge-pill {{ get_color(category ) }}">
                                                {{ src["ext"] }}
                                            </span>
                                        {% endif %}
                                        {# File path #}
                                        <div class="text-muted" title="{{ path }}" style="font-size: 10px;">
                                            <a title="See files from this website"
                                               href="/website/{{ src["website_id"] }}">{{ src["website_url"] }}</a>{{ hl_path|safe }}
                                        </div>
                                    </td>
                                    {# File size & date #}
                                    <td style="white-space: nowrap; vertical-align: top; text-align: right; font-size: 14px">
                                        <div>{{ src["size"] | filesizeformat if src["size"] >= 0 else "?" }}</div>
                                        <code>{{ src["mtime"] | date_format }}</code>
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% if results["hits"]["total"] > (p + 1) * per_page %}
                        <button class="btn btn-primary" onclick="nextPage()" style="float: right">Next</button>
                    {% endif %}
                    {% if p > 0 %}
                        <button class="btn btn-primary" onclick="prevPage()">Previous</button>
                    {% endif %}

                </div>
            </div>
        {% else %}
            <div class="card">
                <div class="card-body">
                    <p>No results.</p>
                    <p>For better results:</p>
                    <ul>
                        <li>Try checking the 'Match any word' box for a broader search.</li>
                        <li>Make sure you don't include the file extension in your query (Use the appropriate field to
                            filter file types)
                        </li>
                        <li>If you're searching for files in a particular website, use the <a href="/website">website
                            search page</a></li>
                    </ul>
                </div>

            </div>
        {% endif %}


        <script src="/static/js/report.js"></script>
        <script>
            $('[data-toggle="popover"]').popover({
                trigger: "focus",
                delay: {"show": 0, "hide": 100},
                placement: "right",
                html: true
            });

            //Size slider
            $("#sizeSlider").ionRangeSlider({
                type: "double",
                grid: false,
                force_edges: true,
                min: 0,
                max: 3684.03149864,
                from: {{ size_min ** (1 / 3) if size_min else 0 }},
                to: {{ (size_max ** (1 / 3)) if size_max else 3684.03149864}},
                min_interval: 5,
                drag_interval: true,
                prettify: function (num) {

                    if (num === 0) {
                        return "0 B"
                    } else if (num >= 3684) {
                        return humanFileSize(num * num * num) + "+";
                    }

                    return humanFileSize(num * num * num)
                },
                onFinish: function (e) {
                    let size_min = (e.from * e.from * e.from);
                    let size_max = (e.to * e.to * e.to);

                    if (e.to >= 3684) {
                        size_max = null;
                    }

                    document.getElementById("sizeMin").value = size_min;
                    document.getElementById("sizeMax").value = size_max;
                }
            });
            //Date slider
            $("#dateSlider").ionRangeSlider({
                type: "double",
                grid: false,
                force_edges: true,
                min: 0,
                max: Math.floor(Date.now() / 1000),
                from: {{ date_min if date_min else 0 }},
                to: {{ date_max if date_max else "self.max"}},
                min_interval: 3600 * 24 * 7,
                step: 3600 * 24,
                drag_interval: true,
                prettify: function (num) {
                    let date = (new Date(num * 1000));
                    return date.getUTCFullYear() + "-" + ("0" + (date.getUTCMonth() + 1)).slice(-2) + "-" + ("0" + date.getUTCDate()).slice(-2)
                },
                onFinish: function (e) {
                    document.getElementById("dateMin").value = e.from;
                    document.getElementById("dateMax").value = e.to >= e.max ? null : e.to;
                }
            });

            //Next button
            function nextPage() {
                document.getElementById("page").value = parseInt(document.getElementById("page").value) + 1;
                document.getElementById("sfrm").submit();
            }

            function prevPage() {
                document.getElementById("page").value = parseInt(document.getElementById("page").value) - 1;
                document.getElementById("sfrm").submit();
            }

        </script>
    </div>

{% endblock body %}
