<template>
  <div>
    <div v-if="product.product_id" class="buttons has-addons is-centered">
      <a :href="`/wp-admin/post.php?post=${product.product_id}&action=edit`" target="_blank" class="button">
        <b-icon icon="pencil" size="is-small" />
      </a>
      <button class="button" @click="onUpdate(product.numref)">
        <b-icon icon="sync" size="is-small" type="is-info" />
      </button>
      <button class="button" @click="onDestroy(product.numref)">
        <b-icon icon="delete" size="is-small" type="is-danger" />
      </button>
    </div>
    <div v-else class="buttons has-addons is-centered">
      <button class="button" @click="onCreate(product.numref)">
        <b-icon icon="plus" size="is-small" type="is-success" />
      </button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from "@vue/composition-api";
import { useRPSync } from "../composables/rpsync";
import { ProductData } from "../types/rpsync";

export default defineComponent({
  props: {
    product: {
      type: Object as PropType<ProductData | null>,
      default: () => null,
    },
  },
  setup({ product }, { root }) {
    const { create, update, destroy, fetch } = useRPSync();
    const { $buefy } = root;

    const onCreate = async (numref: string) => {
      try {
        await create(numref);
        $buefy.snackbar.open({
          type: "is-success",
          message: `Le produit ${numref} a été créé.`,
          queue: false,
        });
        await fetch();
      } catch (error: any) {
        $buefy.snackbar.open({ type: "is-danger", message: error.message, queue: false });
      }
    };
    const onUpdate = async (numref) => {
      try {
        await update(numref);
        $buefy.snackbar.open({
          type: "is-success",
          message: `Le produit ${numref} a été mis à jour.`,
          queue: false,
        });
      } catch (error: any) {
        $buefy.snackbar.open({ type: "is-danger", message: error.message, queue: false });
      }
    };
    const onDestroy = async (numref) => {
      $buefy.dialog.confirm({
        message: "Confirmer la suppression ?",
        onConfirm: async () => {
          try {
            await destroy(numref);
            $buefy.snackbar.open({
              type: "is-success",
              message: `Le produit ${numref} a été supprimé.`,
              queue: false,
            });
            await fetch();
          } catch (error: any) {
            $buefy.snackbar.open({ type: "is-danger", message: error.message, queue: false });
          }
        },
      });
    };
    return { onCreate, onUpdate, onDestroy };
  },
});
</script>
