import { TEMPLATE_LIST } from "../../config/ApiUrl";
import coreLibrary from "../../../core/helpers/CoreLibrary";
import { CONTENT_GENERATOR_FORM } from "../../config/ApiUrl";
import FavoriteTemplateMixin from "./FavoriteTemplateMixin";
import { urlGenerator } from "../../helpers/AxiosHelper";

export default {
  extends: coreLibrary,
  mixins: [FavoriteTemplateMixin],
  data() {
    return {
      activeCategory: "All",
      categories: [],
      catWiseTemplates: [],
      alertModalShow: false,
      templatePreloader: false,
    };
  },
  created() {
    this.getTemplateList();
    this.$store.dispatch("getAiSettings");
  },
  methods: {
    getTemplateList() {
      this.templatePreloader = true;
      this.axiosGet(TEMPLATE_LIST).then((response) => {
        this.catWiseTemplates = response.data.data;
        this.setCategories();
        this.templatePreloader = false;
      });
    },
    setCategories() {
      for (const key in this.catWiseTemplates) {
        this.categories.push(key);
      }
    },
    activeCatItemEvent(value) {
      this.activeCategory = value;
      this.$store.dispatch("increaseTemplateIndex");
    },
    handleTemplateClick(slug) {
      if (this.openAiConfig && this.openAiKey) {
        window.location.href = urlGenerator(`${CONTENT_GENERATOR_FORM}/${slug}`);
      } else {
        this.alertModalShow = true;
      }
    },
    aiAlertModalClosed() {
      this.alertModalShow = false;
    },
  },
  computed: {
    templateList() {
      let templates = [];
      if (this.activeCategory == "All") {
        for (const key in this.catWiseTemplates) {
          templates = templates.concat(this.catWiseTemplates[key]);
        }
      } else {
        templates = this.catWiseTemplates[this.activeCategory];
      }
      templates.sort(function (a, b) {
        let nameA = a.name.toUpperCase();
        let nameB = b.name.toUpperCase();
        if (nameA > nameB) return 1;
        if (nameA < nameB) return -1;
        return 0;
      });

      let favoriteTemplates = [];
      let regularTemplates = [];

      for (const template of templates) {
        this.favoriteTemplateList.includes(template.id)
          ? favoriteTemplates.push(template)
          : regularTemplates.push(template);
      }
      return favoriteTemplates.concat(regularTemplates);
    },
    templateIndex() {
      return this.$store.getters.templateIndex;
    },
    openAiKey() {
      return this.$store.getters.aiSettings.open_ai_key ? true : false;
    },
    openAiConfig() {
      return +this.$store.getters.aiSettings.open_ai_config ? true : false;
    },
  },
};
