<template>
  <div>
    <div class="form-group">
      <label for="name">عنوان موضوع: </label>
      <input
        type="text"
        class="form-control"
        id="name"
        placeholder="عنوان موضوع"
        v-model.trim="title"
      />
    </div>
    <div class="w-100 d-flex justify-content-between align-items-center">
      <button
        @click.prevent="deleteCat()"
        class="btn delete-btn btn-outline-danger"
        type="button"
      >
        حذف
      </button>
      <button @click.prevent="saveCat()" type="button" class="btn btn-primary">
        ذخیره
      </button>
    </div>
  </div>
</template>
<script>
import { mapState } from "pinia";
import favoriteApi from "~/apis/favoriteApi";


export default {
  props: {
    activeTab: null,
    editCat: null,
    categories: {
      default() {
        return [];
      },
    },
  },
  beforeMount() {
    this.httpService = new HttpService(import.meta.env.VITE_BASE_URL);
  },
  mounted() {
    this.title = this.editCat ?? null;
  },

  data() {
    return {
      title: null,
      httpService: undefined,
      loading: false,
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
    };
  },
  computed: {
    ...mapState({
      activeSchemaGetter: "activeSchemaGetter",
    }),
    ...mapState("favorite", [
      "listTakenFromTreeGetter",
      "activeEventTreeListGetter",
    ]),
  },
  methods: {
    saveCat() {
      let payload = {};
      let url = repoUrl() + favoriteApi.favorite.setCategories;
      url = url.replace("@data_type", this.activeTab);

      // update categories by new title.(edit mode)
      if (this.editCat) {
        this.categories.forEach((value, index) => {
          if (value == this.editCat) {
            this.categories[index] = this.title;
          }
        });

        payload = {
          tags: [...this.categories],
        };
      } else {
        // create mode
        payload = {
          tags: [...this.categories, this.title],
        };
      }

      this.httpService.postRequest(url, payload).then((res) => {
        setTimeout(() => {
          this.$emit("close");
        }, 500);
      });
    },
    deleteCat() {
      let url = repoUrl() + favoriteApi.favorite.setCategories;
      url = url.replace("@data_type", this.activeTab);

      let payload = {
        tags: this.categories.filter((item) => item != this.title),
      };

      this.httpService.postRequest(url, payload).then((res) => {
        setTimeout(() => {
          this.$emit("close");
        }, 500);
      });
    },
  },
};
</script>
<style lang="scss"></style>
