<script>
import Swal from "sweetalert2";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
import { ObjectsGlobal } from "@/components/session/token/SessionUser/Objects/ObjectsGlobal.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import {ref} from "vue";

/**
 * Local economic product cache
 * @type {ref<null>}
 */
export const economic_products_cache = ref(null);

/**
 * Get the Economic Product name
 * @param id
 * @returns {string}
 */
export const getEconomicProductName = (id) => {
  if (economic_products_cache.value === null) {
    economic_products_cache.value = [];
    SessionUser.objects.economic_products.get.all().then((departments) => {
      economic_products_cache.value = departments;
    });
  }
  const object = economic_products_cache.value.find((object) => object.id === parseInt(id));
  return object ? object.name : SessionUser.objects.global.language.no_data;
}

/**
 * The Economic Products object
 */
export const EconomicProducts = {
  meta: {
    title: "E-conomic produkter",
    icon: "fas fa-list",
    description: "Oversigt over e-conomic produkter",
    endpoint: "/economic/products",
    labels: {
      single: "e-conomic produkt",
      multiple: "e-conomic produkter"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    name: {
      label: "Navn",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(EconomicProducts.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(EconomicProducts.meta.endpoint, id);
    }
  },
  functions: {
    getEconomicProductName: getEconomicProductName,
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(EconomicProducts, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(EconomicProducts, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        EconomicProducts,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};
</script>