<template>
  <modal :open="open">
    <template #body>
      <form @submit.prevent="">
        <select-field
          v-model="bookmark.bookmarkCategoryId"
          label="Category"
          :items="selectCategories"
          emptyLabel="No Category"
        />
        <text-field required v-model="bookmark.bookmarkName" label="Name" />
        <text-field required v-model="bookmark.url" label="URL" />
      </form>
    </template>
    <template #actions>
      <btn @click="delBookmark" label="Delete" danger v-if="!!this.bookmark.id" />
      <btn @click="close" label="Cancel" />
      <btn primary :label="saveLabel" :disabled="!allowSave" type="button" @click="save" />
    </template>
  </modal>
</template>
<script>
import TextField from "./TextField.vue";
import Modal from "./Modal.vue";
import axios from "axios";
import Btn from "./Button.vue";
import SelectField from "./SelectField.vue";

export default {
  components: { TextField, Modal, Btn, SelectField },
  props: ["open", "mode", "data", "categories"],
  watch: {
    data: function (next) {
      if (next) {
        this.bookmark = JSON.parse(JSON.stringify(next));
      }
    },
  },
  data() {
    return {
      bookmark: {},
    };
  },
  computed: {
    saveLabel() {
      return this.bookmark.id ? "Update" : "Save";
    },
    selectCategories() {
      return this.categories.map((i) => ({ label: i.categoryName, value: i.id }));
    },
    allowSave() {
      return this.bookmark.bookmarkName && this.bookmark.url
    }
  },
  methods: {
    close() {
      this.$emit("close");
    },
    async delBookmark() {
      let resp = await axios.delete(
        `/api/bookmarks/${this.bookmark.id}`,
        this.bookmark
      );
      if (resp.status == 200) {
        this.$emit("update");
      }
    },
    async save() {
      if (this.bookmark.id) {
        let resp = await axios.put(
          `/api/bookmarks/${this.bookmark.id}`,
          this.bookmark
        );
        if (resp.status == 200) {
          this.$emit("update");
        }
      } else {
        let resp = await axios.post("/api/bookmarks", {
          active: true,
          ...this.bookmark,
        });
        if (resp.status == 200) {
          this.$emit("update");
        }
      }
    },
  },
};
</script>
