{% 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 - 2.5rem);
        }
    }

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

    ul {
        line-height: 2.25rem;
    }

    .note,
    video {
        box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.25);
    }

    .note {
        border-radius: 7.5px;
        padding-left: 1.25rem;
        padding-right: 1.25rem;
        padding-top: 1.25rem;
        padding-bottom: 1.25rem;
        width: calc(60vw - 2.5rem);
        margin-bottom: 1rem;
        border: 1px solid rgba(0, 0, 0, 0.17);
    }

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

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

    .note>.body>span {
        margin-right: 5px;
    }

    .note>.body>button {
        padding-top: 5px;
        padding-bottom: 5px;
        font-size: 0.75rem;
    }

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

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

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

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

    .top>.timestamp {
        color: #098fb4;
        margin-top: 0;
        margin-bottom: 0;
    }

    @media (prefers-color-scheme: dark) {
        .note {
            background-color: rgba(255, 255, 255, 0.0225);
        }

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

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

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

{% block content %}
<div id="content">
    <!-- Video -->
    <video src="{{ url_for('routes.archive_video', name=name, file=video.filename()) }}" id="player" autoplay
        controls></video>
    <!-- Information -->
    <h1 title="Title of the video">{{ video.title.current() }}</h1>
    <div class="info">
        {% set views = video.views.current() %}
        <p>
            <!-- View count -->
            <span title="View count of the video">{{ views }} view{% if views != 1 %}s{% endif %}</span>
            <!-- Uploaded -->
            <span class="spacer">•</span>
            <span title="Upload time of the video">{{ video.uploaded.strftime("%d/%m/%Y") }}</span>
            <!-- Updated -->
            {% if video.updated() %}
            <span class="spacer">•</span>
            <span title="There's been a major change to this video">🌀</span>
            {% endif %}
        </p>
        <p>
            <!-- Youtube link -->
            <a title="Open the video on YouTube" href="https://www.youtube.com/watch?v={{ video.id }}">🔗</a>
            <!-- Download link -->
            <span class="spacer">•</span>
            <a title="Save the video to downloads"
                href="{{ url_for('routes.archive_video', name=name, file=video.filename()) }}" download>💾</a>
            <!-- Like count -->
            {% set likes = video.likes.current() %}
            {% if likes or likes == 0 %}
            <span class="spacer">•</span>
            <span title="Like count of the video">👍 {{ likes }}</span>
            {% 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 title="Show the current description of this video"
        onclick="toggleButton('description', 'description', this)">Show description</button>
    <p id="description" style="display: none;">
        {% for line in description %}
        {{ line }}<br />
        {% endfor %}
    </p>
    {% endif %}
    <!-- Create Note -->
    <h2>Create Note</h2>
    <div class="note">
        <div class="top">
            <p title="Title of the note" class="title createnote-input" contenteditable="true"
                data-placeholder="Title here.."></p>
            <p title="Timestamp to set the note to" id="timestamp-new" class="timestamp" contenteditable="true">00:00
            </p>
        </div>
        <p title="Optional further information for the note" 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>
        // Constantly updates timestamp to video pos
        function updateTimestamp() {
            function formatTime(timestamp) {
                const minutes = Math.floor(timestamp / 60).toString().padStart(2, "0")
                const seconds = Math.max((Math.round(timestamp % 60 - 1.5)), 0).toString().padStart(2, "0")
                return `${minutes}:${seconds}`
            }

            let video = document.getElementById("player");
            let timestamp = document.getElementById("timestamp-new")
            video.addEventListener("timeupdate", function () {
                timestamp.innerText = formatTime(video.currentTime)
            });
        }

        // Creates note by fetching to the api
        function createNote(el) {
            // Get top class
            const top = el.getElementsByClassName("top")[0]

            // Get title
            const title = top.getElementsByClassName("title")[0].innerText
            if (title == "") {
                addError("You must give the note a title before adding it")
                return
            }

            // Get timestamp
            const 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: "POST",
                body: JSON.stringify({
                    title: title, body: body, timestamp: timestamp
                }),
                headers: {
                    "Content-Type": "application/json"
                }
            }).then(() => {
                // Reload to see new note and keep timestamp
                const location = new URL(window.location);
                location.searchParams.append("timestamp", timestamp)
                window.location.replace(location)
            })
        }

        // Immediately start updating the timestamp
        updateTimestamp()
    </script>
    <!-- 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 %}
    <!-- Notes -->
    {% if video.notes %}
    <h2 id="notes-title">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>
        <!-- Body content -->
        <p class="body" contenteditable="true">
            <!-- Optional user-defined body -->
            {% if note.body %}<span>{{ note.body }}</span>{% endif %}
            <!-- Delete button -->
            <button onclick="deleteNote(this.parentElement.parentElement)">Delete</button>
        </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()
        }

        // Deletes note using it's identifier
        function deleteNote(el) {
            // Get identifier
            const id = el.getElementsByClassName("id")[0].innerText

            // Send request to current route
            fetch("", {
                method: "DELETE",
                body: JSON.stringify({
                    id
                }),
                headers: {
                    "Content-Type": "application/json"
                }
            })

            // Delete note from DOM
            el.remove()

            // Delete the note heading from DOM if there aren't any notes
            if (document.getElementsByClassName("note").length == 1) {
                const notesHeader = document.getElementById("notes-title")
                notesHeader.remove()
            }
        }

        // Jump to timestamp on startup if requested in query
        const urlParams = new URLSearchParams(window.location.search);
        const timestampParam = urlParams.get("timestamp");
        if (timestampParam != undefined && timestampParam != null) {
            toTimestamp(parseInt(timestampParam));
        }

        // Listen for `focusout` event on note title or body
        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 %}