<template>
  <modal :open="open">
    <template #body>
      <form @submit.prevent="save">
        <text-field v-model="category.categoryName" label="Name" />
        <icon-picker v-model="category.glyph" />
      </form>
    </template>
    <template #actions>
      <btn @click="delCategory" label="Delete" danger v-if="!!this.category.id" />
      <btn @click="close" label="Cancel" />
      <btn @click="submit" :label="saveLabel" />
    </template>
  </modal>
</template>
<script>
import TextField from "./TextField.vue";
import Modal from "./Modal.vue";
import IconPicker from "./IconPicker.vue";
import axios from "axios";
import Btn from "./Button.vue";

export default {
  components: { TextField, Modal, IconPicker, Btn },
  props: ["open", "mode", "data"],
  watch: {
    data: function (next) {
      if (next) {
        this.category = JSON.parse(JSON.stringify(next));
      }
    },
  },
  data() {
    return {
      category: {},
    };
  },
  computed: {
    saveLabel() {
      return this.category.id ? "Update" : "Save";
    },
  },
  methods: {
    close() {
      this.$emit("close");
    },
    async delCategory() {
      let resp = await axios.delete(
        `/api/application_categories/${this.category.id}`,
        this.category
      );
      if (resp.status == 200) {
        this.$emit("update");
      }
    },
    async submit() {
      if (this.category.id) {
        let resp = await axios.put(
          `/api/application_categories/${this.category.id}`,
          this.category
        );
        if (resp.status == 200) {
          this.$emit("update");
        }
      } else {
        let resp = await axios.post("/api/application_categories", {
          active: true,
          ...this.category,
        });
        if (resp.status == 200) {
          this.$emit("update");
        }
      }
    },
  },
};
</script>
