
<template>
  <modal :open="open">
    <template #body>
      <form @submit.prevent="">
        <select-field
          v-model="app.applicationCategoryId"
          label="Category"
          :items="selectCategories"
          emptyLabel="No Category"
        />
        <text-field v-model="app.appName" label="Name" />
        <text-field v-model="app.description" label="Description" />
        <text-field v-model="app.url" label="URL" />
        <icon-picker v-model="app.glyph" />
      </form>
    </template>
    <template #actions>
      <btn @click="delApp" label="Delete" danger v-if="!!this.app.id" />
      <btn @click="close" label="Cancel" />
      <btn :label="saveLabel" type="button" @click="save" />
    </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";
import SelectField from "./SelectField.vue";

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