{% extends "base.html" %}
{% load helpers %}
{% load static %}
{% load ui_framework %}

{% block extra_styles %}
    <style>
        .tile-header {
            display: block;
            min-height: 85px;  /* allow room for two rows of tags */
        }

        .tile-header h2 {
            margin-bottom: 5px;
            margin-top: 0;
        }

        .tile-actions-placeholder {
            height: 30px;
            margin-left: 3px;
            width: 35px;
        }

        .tile-description {
            margin-top: 10px;
            min-height: 72px;  /* allow room for three rows of text */
        }

        .tile-actions {
            position: absolute;
            right: 21px;
            top: 21px;
        }

        .tile-actions .btn {
            padding: 3px 8px;  /* Enlarge action buttons to 32px x 32px */
        }

        .app-details {
            column-gap: 20px;
            display: flex;
            flex-wrap: wrap;
        }

        .app-details dt {
            margin-top: 20px;
        }

        .app-details ul {
            list-style: none;
            padding: 0;
        }

        .app-details > :last-child {
            flex: 1;
        }
    </style>
{% endblock %}

{% block document_title %}{% render_title "plain" %}{% endblock %}

{% block content %}
    <div class="row noprint">
        <div class="col-md-12">
            {% render_breadcrumbs %}
        </div>
    </div>

    <div class="pull-right noprint">
        <a class="btn btn-primary" href="{% url 'apps:apps_list' %}">See Installed Apps</a>
    </div>

    <h1>{% block page_heading %}{% render_title %}{% endblock page_heading %}</h1>

    <div class="row">
        <div class="col-md-12">
            <section class="tiles">
                {% for app in apps %}
                    <div style="position: relative;">
                        <a class="tile clickable" data-app="{{ app.package_name }}" href="?app={{ app.package_name }}">
                            <header class="tile-header">
                                <img
                                    alt="{{ app.name }}"
                                    src="{% if app.icon|default:None != None %}{{ app.icon }}{% else %}{% static 'img/nautobot_icon_192x192.png' %}{% endif %}"
                                    height="64"
                                    width="64"
                                />

                                <!--
                                   Occupy `.tile-actions` dedicated space with `.tile-actions-placeholder`. See comment
                                   above `.tile-actions` element for detailed explanation of this solution and why it
                                   is required here.
                                -->
                                <div aria-hidden="true" class="tile-actions-placeholder pull-right"></div>

                                <h2>{{ app.name }}</h2>

                                {% for use_case in app.use_cases %}
                                    <label class="label label-default">{{ use_case }}</label>
                                {% endfor %}
                            </header>

                            <p class="tile-description">{{ app.headline }}</p>

                            <footer class="tile-footer">
                                <div>By: {{ app.author }}</div>
                                <div>
                                    {% if app.installed %}<label class="label label-success">Installed</label>{% endif %}
                                    <label class="label label-transparent">{{ app.availability }}</label>
                                </div>
                            </footer>
                        </a>

                        <!--
                            Place app action links outside the "main" `a` tile to adhere to HTML rule that forbid
                            nesting anchors within anchors. Absolutely position the actions to make them appear inside
                            the tile though. Fill their dedicated space with `.tile-actions-placeholder` element.
                        -->
                        <div class="tile-actions">
                            {% if app.docs|default:None != None %}
                                <a href="{{ app.docs }}" class="btn btn-info btn-xs" target="_blank" title="Docs">
                            {% else %}
                                <a href="" class="btn btn-info btn-xs disabled" target="_blank" title="No docs provided">
                            {% endif %}
                            <i class="mdi mdi-book-open-page-variant"></i>
                        </a>
                    </div>
                    </div>

                    <div class="modal fade" tabindex="-1" id="modal-{{ app.package_name }}">
                        <div class="modal-dialog modal-lg" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>

                                    <h4 class="modal-title">
                                        {{ app.name }}
                                        {% if app.installed %}<label class="label label-success">Installed</label>{% endif %}
                                    </h4>
                                </div>

                                <div class="modal-body">
                                    <div class="app-details">
                                        <div>
                                            <img
                                                alt="{{ app.name }}"
                                                src="{% if app.icon|default:None != None %}{{ app.icon }}{% else %}{% static 'img/nautobot_icon_192x192.png' %}{% endif %}"
                                                height="64"
                                                width="64"
                                            />

                                            <dl>
                                                <dt class="text-muted text-uppercase">By</dt>
                                                <dd>{{ app.author }}</dd>

                                                <dt class="text-muted text-uppercase">License</dt>
                                                <dd><label class="label label-transparent">{{ app.availability }}</label></dd>

                                                {% if app.requires|length > 0 %}
                                                    <dt class="text-muted text-uppercase">Requirements</dt>
                                                    <dd>
                                                        <ul>
                                                            {% for requirement in app.requires %}
                                                                {% for required_app in apps %}
                                                                    {% if required_app.package_name == requirement %}
                                                                        <li>
                                                                            <a
                                                                                data-app="{{ required_app.package_name }}"
                                                                                href="?app={{ required_app.package_name }}"
                                                                            >
                                                                                {{ required_app.name }}
                                                                            </a>
                                                                        </li>
                                                                    {% endif %}
                                                                {% endfor %}
                                                            {% endfor %}
                                                        </ul>
                                                    </dd>
                                                {% endif %}

                                                <dt class="text-muted text-uppercase">Package name</dt>
                                                <dd><code>{{ app.package_name }}</code></dd>
                                            </dl>
                                        </div>

                                        <div>
                                            <h5>{{ app.headline }}</h5>

                                            <p>{{ app.description|render_markdown }}</p>

                                            {% if app.docs|default:None != None %}
                                                <p>
                                                    <span>
                                                        Docs:
                                                        <a href="{{ app.docs }}" target="_blank">{{ app.docs }}</a>
                                                    </span>
                                                </p>
                                            {% endif %}

                                            {% if app.availability == "NTC License" %}
                                                <p>
                                                    <strong>
                                                        This Nautobot App requires a license to use.
                                                        <a href="https://networktocode.com/contact/" target="_blank">
                                                            Reach out to Network to Code
                                                        </a>
                                                        for more information.
                                                    </strong>
                                                </p>
                                            {% endif %}

                                            <div>
                                                {% for use_case in app.use_cases %}
                                                    <label class="label label-default">{{ use_case }}</label>
                                                {% endfor %}
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="modal-footer">
                                    <button class="btn btn-primary" data-dismiss="modal" type="button">
                                        Done
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            </section>
            <div class="clearfix"></div>
        </div>
    </div>
{% endblock %}

{% block javascript %}
    {{ block.super }}
    <script>
        (function () {
            let previousApp = new URLSearchParams(window.location.search).get("app");
            function toggleAppModal(app, action) {
                if (app) {
                    const appModal = app ? document.querySelector(`#modal-${app}`) : null;
                    const isShown = $(appModal).data("bs.modal")?.isShown;

                    if (action === "hide" ? isShown : !isShown) {
                        $(appModal).modal(action);
                    }

                    previousApp = action === "hide" ? null : app;
                }
            }

            const appTilesContainer = document.querySelector(".tiles");
            const appModals = appTilesContainer.querySelectorAll(".modal");
            const appModalLinks = appTilesContainer.querySelectorAll("a[data-app]");

            for (const appModal of appModals) {
                $(appModal).on("hide.bs.modal", function () {
                    const searchParams = new URLSearchParams(window.location.search);
                    if (searchParams.get('app') === appModal.id.replace(/^modal-/, '')) {
                        searchParams.delete('app');
                        const nextSearch = searchParams.size > 0 ? `?${searchParams.toString()}` : '';
                        const nextURL = `${window.location.pathname}${nextSearch}${window.location.hash}`;
                        history.pushState(history.state, "", nextURL);
                    }

                    previousApp = null;
                });
            }

            for (const appModalLink of appModalLinks) {
                appModalLink.addEventListener("click", (event) => {
                    event.preventDefault();
                    history.pushState(history.state, "", appModalLink.href);

                    toggleAppModal(previousApp, "hide");
                    toggleAppModal(new URL(appModalLink.href).searchParams.get("app"), "show");
                });
            }

            window.addEventListener("popstate", function onPopState() {
                const searchParams = new URLSearchParams(window.location.search);
                const currentApp = searchParams.get("app");

                toggleAppModal(previousApp, 'hide');
                toggleAppModal(currentApp, 'show');
            });

            toggleAppModal(new URLSearchParams(window.location.search).get("app"), "show");
        })();
    </script>
{% endblock javascript %}
