<script setup>
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
const route = useRoute();
const router = useRouter();

// make references
const loading = ref(true);
const post = ref(null);
const emit = defineEmits(["title"]);

// get post
const getPost = async () => {
  fetch(`${import.meta.env.VITE_BACKEND_URL}/post/${route.params.postID}`)
    .then((res) => {
      return res.json();
    })
    .then((json) => {
      loading.value = false;
      post.value = json.post;
      emit("title", `Editing « ${json.post.title} »`);
    });
};

getPost();

const savePost = async (title, text) => {
  let newTitle, newText;

  title ? (newTitle = title) : (newTitle = post._rawValue.title);
  text ? (newText = text) : (newText = post._rawValue.text);

  // create JSON object and proper headers
  const options = {
    method: "PUT",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json;charset=UTF-8",
    },
    credentials: "include",
    body: JSON.stringify({
      title: newTitle,
      text: newText,
      published: post._rawValue.published,
    }),
  };

  // send to backend
  fetch(
    `${import.meta.env.VITE_BACKEND_URL}/post/${route.params.postID}`,
    options
  ).then((res) => {
    // if everything sent ok
    if (res.ok) {
      // fetch new posts
      getPost();
      // redirect
      router.push(`/post/${route.params.postID}`);
    } else {
      alert("Errors encountered!");
    }
  });
};
</script>

<template>
  <div class="w-full flex flex-col items-center mt-10">
    <div
      class="h-full flex flex-col justify-center items-center"
      v-if="loading"
    >
      <p class="text-3xl loading">
        Loading<span>.</span><span>.</span><span>.</span>
      </p>
    </div>
    <div class="flex flex-col align-center w-full items-center" v-else>
      <div class="flex items-center justify-center mb-10 gap-10">
        <label for="post_title">Title:</label>
        <input
          id="post_title"
          class="bg-zinc-900 border p-5"
          v-model="postTitle"
          :placeholder="post.title"
        />
      </div>
      <textarea
        v-model="postText"
        class="bg-zinc-900 border p-5 mb-10 w-2/3"
        rows="4"
        :placeholder="post.text"
      ></textarea>
      <div class="flex items-center justify-center gap-10">
        <button
          @keydown.enter="savePost(postTitle, postText)"
          @click="savePost(postTitle, postText)"
          class="hover:bg-emerald-700 py-5 w-[8rem] flex justify-center border"
        >
          &#x1F4BE; Save
        </button>
      </div>
    </div>
  </div>
</template>
