
<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" required />
        <text-field v-model="app.description" label="Description" />
        <text-field v-model="app.url" label="URL" required />
        <switch-field v-model="app.favicon" label="Use favicon" />
        <icon-picker v-model="app.glyph" v-if="!app.favicon" />
        <switch-field v-model="app.enableHealthcheck" label="Health check" />
      </form>
    </template>
    <template #actions>
      <btn @click="delApp" label="Delete" danger v-if="!!this.app.id" />
      <btn @click="close" label="Cancel" />
      <btn :disabled="!saveAllowed" primary :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";
import SwitchField from './Switch.vue';

export default {
  components: { TextField, Modal, IconPicker, Btn, SelectField, SwitchField },
  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 }));
    },
    saveAllowed() {
      return (!!this.app.appName && !!this.app.url)
    }
  },
  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,
          enableHealthcheck: !!this.app.enableHealthcheck,
          favicon: !!this.app.favicon,
          ...this.app,
        });
        if (resp.status == 200) {
          this.$emit("update");
        }
      }
    },
  },
};
</script>
