{% extends 'base.html' %}

{% block styling %}
<style>
    body {
        margin-bottom: 3rem;
    }

    video {
        margin-top: 8vh;
        border-radius: 0.75rem;
    }

    .info {
        color: #7f7f7f;
        display: flex;
        justify-content: space-between;
    }

    .info>p {
        margin-top: 0;
    }

    h1 {
        margin-bottom: 0.75rem;
    }

    canvas {
        width: 50vw;
    }

    #description,
    .metadata {
        font-size: 0.9rem;
        line-height: 1.25rem;
        color: #595959;
        margin-left: 1rem;
    }


    .metadata {
        display: none;
        margin-top: -0.65rem;
        margin-bottom: 0.65rem;
    }

    video,
    h1,
    #description,
    .info {
        width: 60vw;
    }

    @media screen and (max-width: 850px) {

        video,
        h1,
        canvas,
        #description,
        .info {
            width: 80vw;
        }

        .note {
            width: calc(80vw - 2rem);
        }
    }

    .spacer {
        margin-left: 0.5rem;
        margin-right: 0.5rem;
    }

    ul {
        line-height: 2.25rem;
    }

    .note {
        border: 1px solid rgba(0, 0, 0, 0.12);
        border-radius: 0.5rem;
        padding-left: 1rem;
        padding-right: 1rem;
        width: calc(60vw - 2rem);
        margin-bottom: 1rem;
    }

    .note>.id {
        font-size: 0.75rem;
        color: #7e7e7e;
        margin-top: 0;
    }

    .note>.body {
        margin-bottom: 0.75rem;
        font-size: 0.9rem;
    }

    .top {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .top>.title {
        font-weight: bold;
        font-size: 1.2rem;
        margin-top: 0.75rem;
        margin-bottom: 0;
        min-width: 50vw;
    }

    .createnote-input:empty:not(:focus)::before {
        content: attr(data-placeholder);
    }

    .createnote-button {
        margin-top: 0.25rem;
        margin-bottom: 1rem;
    }

    .top>.timestamp {
        color: #098fb4;
    }

    @media (prefers-color-scheme: dark) {

        #description,
        .metadata {
            color: rgb(181, 181, 181);
        }

        /* copy of base.html stuff */
        .note {
            background-color: transparent;
            border: 1px solid rgba(255, 255, 255, 0.12);
        }

        .note>.id {
            color: rgb(181, 181, 181);
        }

        .top>.timestamp {
            color: #4bc0c0;
        }
    }
</style>
{% endblock %}

{% block content %}
<div id="content">
    <!-- Video -->
    <video src="/archive/{{ video.channel.path }}/videos/{{ video.id }}.mp4" id="player" autoplay controls></video>
    <!-- Information -->
    <h1>{{ video.title.current() }}</h1>
    <div class="info">
        {% set views = video.views.current() %}
        <p>
            <!-- View count -->
            {{ views }} view{% if views != 1 %}s{% endif %}
            <!-- Uploaded -->
            <span class="spacer">•</span>
            {{ video.uploaded.strftime("%d/%m/%Y") }}
            <!-- Updated -->
            {% if video.updated() %}
            <span class="spacer">•</span>
            🌀
            {% endif %}
        </p>
        <p>
            <!-- Youtube link -->
            <a href="https://www.youtube.com/watch?v={{ video.id }}">🔗</a>
            <!-- Download link -->
            <span class="spacer">•</span>
            <a href="/archive/{{ video.channel.path }}/videos/{{ video.id }}.mp4" download>💾</a>
            <!-- Like count -->
            {% set likes = video.likes.current() %}
            {% if likes or likes == 0 %}
            <span class="spacer">•</span>
            👍 {{ likes }}
            {% endif %}
        </p>
    </div>
    <!-- Description -->
    {% set description = video.description.current().split("\n") %}
    {% set no_description = description|count == 1 and description[0] == "" %}
    {% if not no_description %}
    <button onclick="toggleButton('description', 'description', this)">Show description</button>
    <p id="description" style="display: none;">
        {% for line in description %}
        {{ line }}<br />
        {% endfor %}
    </p>
    {% endif %}
    <!-- History -->
    <h2>History</h2>
    {% set mto_title = video.title.inner|count != 1 %}
    {% set mto_description = video.description.inner|count != 1 %}
    {% set mto_views = video.views.inner|count != 1 %}
    {% set mto_likes = video.likes.inner|count != 1 %}
    <ul>
        <!-- Titles -->
        {% if not mto_title and not mto_description %}
        <li>No title or description changes on record</li>
        {% else %}
        {% if mto_title %}
        {% for timestamp in video.title.inner %}
        <li>
            {% if loop.index == video.title.inner|count %}
            Current title has been in place since {{ timestamp.strftime("%d/%m/%Y") }}
            {% else %}
            {% if loop.index == 1 %}
            Title was originally
            {% else %}
            Title changed to
            {% endif %}
            <button onclick="toggleButton('history_title' + {{ loop.index }}, 'title', this)">
                Show title
            </button>
            on {{ timestamp.strftime("%d/%m/%Y") }}
            <span id="history_title{{ loop.index }}" class="metadata">
                <br />{{ video.title.inner[timestamp] }}
            </span>
            {% endif %}
        </li>
        {% endfor %}
        {% else %}
        <li>No title changes on record</li>
        {% endif %}
        <!-- Descriptions -->
        {% if mto_description %}
        {% for timestamp in video.description.inner %}
        <li>
            {% if loop.index == video.description.inner|count %}
            Current description has been in place since {{ timestamp.strftime("%d/%m/%Y") }}
            {% else %}
            {% if loop.index == 1 %}
            Description was originally
            {% else %}
            Description changed to
            {% endif %}
            <button onclick="toggleButton('history_description' + {{ loop.index }}, 'description', this)">
                Show description
            </button>
            on {{ timestamp.strftime("%d/%m/%Y") }}
            <span id="history_description{{ loop.index }}" class="metadata">
                <br />
                {% for line in video.description.inner[timestamp].split("\n") %}
                {{ line }}<br />
                {% endfor %}
            </span>
            {% endif %}
        </li>
        {% endfor %}
        {% else %}
        <li>No description changes on record</li>
        {% endif %}
        {% endif %}
        <!-- Likes/view summary -->
        {% if not mto_views and not mto_likes %}
        <li>No view or like changes on record</li>
        {% elif not mto_views %}
        <li>No view changes on record</li>
        {% elif not mto_likes %}
        <li>No like changes on record</li>
        {% endif %}
    </ul>
    <!-- Graphs -->
    {% if mto_views or mto_likes %}
    {% if mto_views %}
    <h2>Views over time</h2>
    <canvas id="chart_views"></canvas>
    {% endif %}
    {% if mto_likes %}
    <h2>Likes over time</h2>
    <canvas id="chart_likes"></canvas>
    {% endif %}
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script
        src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@next/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
    <script>
        function chart(type, id, data) {
            // Generate config
            const points = {
                labels: Object.keys(data).map(date => new Date(date)),
                datasets: [{
                    label: "# of " + type,
                    data: Object.values(data),
                    fill: false,
                    borderColor: "rgb(75, 192, 192)",
                    tension: 0.1
                }]
            };

            // Get context
            const ctx = document.getElementById(id).getContext("2d");

            // Create chart
            return new Chart(ctx, {
                type: "line",
                data: points,
                options: {
                    responsive: false, // TODO: responsive but still the right width
                    scales: {
                        x: {
                            type: "time",
                            time: {
                                displayFormats: {
                                    quarter: "MMM D (hA)"
                                }
                            },
                        },
                        y: {
                            ticks: {
                                stepSize: 10
                            },
                        }
                    }
                }
            })
        }

        // Get data
        let views_data = {{ views_data| safe }};
        let likes_data = {{ likes_data| safe }};

        // Create charts
        if (Object.keys(views_data).length != 1) {
            chart("Views", "chart_views", views_data);
        }
        if (Object.keys(likes_data).length != 1) {
            chart("Likes", "chart_likes", likes_data);
        }
    </script>
    {% endif %}
    <!-- Create Note -->
    <h2>Create Note</h2>
    <div class="note">
        <div class="top">
            <p class="title createnote-input" contenteditable="true" data-placeholder="Title here.."></p>
            <p class="timestamp" contenteditable="true">00:00</p>
        </div>
        <p class="body createnote-input" contenteditable="true" data-placeholder="Optional message here.."></p>
        <button class="createnote-button" onclick="createNote(this.parentElement)">Add new note</button>
    </div>
    <script>
        // Creates note by fetching to the api
        function createNote(el) {
            // Get top class
            let top = el.getElementsByClassName("top")[0]

            // Get title
            let title = top.getElementsByClassName("title")[0].innerText
            if (title == "") {
                addError("No title provided for element")
            }

            // Get timestamp
            let timestamp = top.getElementsByClassName("timestamp")[0].innerText

            // Get body and clean
            let body = el.getElementsByClassName("body")[0].innerText
            if (body == "") {
                body = null
            }

            // Send request
            fetch("", {
                method: "PUT",
                body: JSON.stringify({
                    title: title, body: body, timestamp: timestamp
                }),
                headers: {
                    "Content-Type": "application/json"
                }
            }).then(resp => resp.json().then(json => {
                // Reload at created id
                window.location.href += "#" + json["id"]
                window.location.reload()
            }))
        }
    </script>
    <!-- Notes -->
    {% if video.notes %}
    <h2>Notes</h2>
    {% for note in video.notes %}
    <div class="note">
        <!-- Top information -->
        <div class="top">
            <!-- Title -->
            <p class="title" contenteditable="true">{{ note.title }}</p>
            <!-- Timestamp -->
            <a href="#player" onclick="toTimestamp({{ note.timestamp|safe }})" class="timestamp">{{
                note.timestamp|timestamp }}</a>
        </div>
        <!-- Identifier -->
        <a href="#{{ note.id }}" id="{{ note.id }}" class="id">{{ note.id }}</a>
        <!-- Optional message -->
        <p class="body" contenteditable="true">{% if note.body %}{{ note.body }}{% else %}{% endif %}</p>
    </div>
    {% endfor %}
    <script>
        // Puts the video player element to the provided timestamp
        function toTimestamp(timestamp) {
            let player = document.getElementById("player")
            player.currentTime = Math.abs(timestamp - 1)
            player.play()
        }

        // Listen for `focusout` event on note title
        document.addEventListener("focusout", (event) => {
            let el = event.srcElement
            if ((el.classList.contains("title") || el.classList.contains("body")) && !el.classList.contains("createnote-input")) {
                // Make payload for title
                let payload = {}
                if (el.classList.contains("title")) {
                    payload["id"] = el.parentElement.parentElement.getElementsByClassName("id")[0].innerText
                    payload["title"] = el.innerText
                } else {
                    payload["id"] = el.parentElement.getElementsByClassName("id")[0].innerText
                    if (el.innerText == "") {
                        payload["body"] = null
                    } else {
                        payload["body"] = el.innerText
                    }
                }

                // Send update
                fetch("", {
                    method: "PATCH",
                    body: JSON.stringify(
                        payload
                    ),
                    headers: {
                        "Content-Type": "application/json"
                    }
                })
            }
        })
    </script>
    {% endif %}
</div>
{% endblock %}

{% block scripts %}
<script>
    function toggleButton(id, name, caller) {
        let el = document.getElementById(id);
        if (el.style.display === "none" || el.style.display === "") {
            caller.innerText = "Hide " + name;
            el.style.display = "block";
        } else {
            caller.innerText = "Show " + name;
            el.style.display = "none";
        }
    }
</script>
{% endblock %}