{% extends "components/base.html" %}
{% block title %}Post{% endblock %}

{% block main_area %}
  <!-- Title -->
  <h1 class="mt-4">{{ post.title }}</h1>
  {% if post.summary %}
    <h5 class="text-muted">{{ post.summary }}</h5>
  {% endif %}
  <!-- Author -->
  <div class="text-muted fst-italic mb-2">{{ post.created_at }}
    <br>
    by.
    {{ post.author | upper }}</div>
  <!-- Rendered Markdown Content -->
  <div id="post-content">
    {{ post.render_markdown|safe }}
  </div>
  <hr>
  {% if post.tags.exists %}
    <i class="fa-solid fa-tags"></i>
    {% for tag in post.tags.all %}
      <span class="badge bg-primary">{{ tag }}</span>
    {% endfor %}
    <br/>
    <br/>
  {% endif %}

  {% if request.user == post.author %}
    <div class="d-flex mt-3">
      <a href="{% url 'blog:post_list' %}" class="btn btn-secondary me-2">List</a>
      <a href="{% url 'blog:update_post' post.pk %}" class="btn btn-warning me-2">Edit</a>
      <form method="POST" action="{% url 'blog:delete_post' post.pk %}" class="d-inline" id="delete-form">
        {% csrf_token %}
        <button type="button" class="btn btn-danger" id="delete-button">Delete</button>
      </form>
    </div>
  {% endif %}

  <!-- Highlight.js Styles -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github-dark.min.css">
  <!-- Highlight.js Script -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
  <script>
    // 문서 로드 후 동작
    document.addEventListener("DOMContentLoaded", async () => {
      // 코드 블럭 하이라이트
      document.querySelectorAll("pre code").forEach((block) => {
        hljs.highlightElement(block);
      });

      await updateImagesWithPresignedUrls();
    });

    // Function to update images with presigned URLs
    async function updateImagesWithPresignedUrls() {
      const contentDiv = document.getElementById("post-content");
      const contentHtml = contentDiv.innerHTML;
      const parser = new DOMParser();
      const doc = parser.parseFromString(contentHtml, "text/html");
      const images = doc.querySelectorAll("img");

      for (const img of images) {
        const objectName = img.getAttribute("src"); // src에 저장된 object_name
        try {
          const response = await fetch("/obs_minio/get_presigned_url/", {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({object_name: objectName})
          });

          if (response.ok) {
            const data = await response.json();
            img.setAttribute("src", data.presigned_url); // Presigned URL로 src 업데이트
          }
        } catch (error) {
          console.error("Error fetching presigned URL:", error);
        }
      }

      // 업데이트된 HTML을 다시 삽입
      contentDiv.innerHTML = doc.body.innerHTML;

      // Reapply syntax highlighting
      document
        .querySelectorAll("pre code")
        .forEach((block) => {
          hljs.highlightElement(block);
        });
    }

    // Delete post
    document
      .getElementById("delete-button")
      .addEventListener("click", function () {
        const confirmed = confirm("Are you sure you want to delete this post?");
        if (confirmed) {
          document
            .getElementById("delete-form")
            .submit();
        }
      });
  </script>
{% endblock %}
