<template>
  <li>
    <button
      class="btn btn-sm btn-secondary"
      @click="modal.showModal = true"
      :title="$t('courselocation.assign_course_address')"
    >
      <i class="fa fa-map-marker" />
    </button>
  </li>

  <teleport to="body">
    <modal
      v-if="modal.showModal"
      :modal-dialog-class="modal.modalDialogClass"
      @close="modal.showModal = false"
    >
      <template #header>
        <h2 class="modal-title">
          {{ $t("courselocation.sure") }}
        </h2>
      </template>
      <template #body>
        <address-render-box :address="person.current_household_address" />
        <p>{{ $t("courselocation.sure_description") }}</p>
      </template>
      <template #footer>
        <button class="btn btn-danger" @click="assignAddress">
          {{ $t("courselocation.ok") }}
        </button>
      </template>
    </modal>
  </teleport>
</template>

<script>
import { mapState } from "vuex";
import Modal from "ChillMainAssets/vuejs/_components/Modal";
import AddressRenderBox from "ChillMainAssets/vuejs/_components/Entity/AddressRenderBox.vue";

export default {
  name: "ButtonLocation",
  components: {
    AddressRenderBox,
    Modal,
  },
  props: ["person"],
  data() {
    return {
      modal: {
        showModal: false,
        modalDialogClass: "modal-dialog-centered modal-md",
      },
    };
  },
  computed: {
    ...mapState({
      context: (state) => state.addressContext,
    }),
  },
  methods: {
    assignAddress() {
      //console.log('assignAddress id', this.person.current_household_address);
      let payload = {
        target: this.context.target.name,
        targetId: this.context.target.id,
        locationStatusTo: "person",
        personId: this.person.id,
      };
      this.$store
        .dispatch("updateLocation", payload)
        .catch(({ name, violations }) => {
          if (name === "ValidationException" || name === "AccessException") {
            violations.forEach((violation) =>
              this.$toast.open({ message: violation }),
            );
          } else {
            this.$toast.open({ message: "An error occurred" });
          }
        });

      window.location.assign("#section-20");
      this.modal.showModal = false;
    },
  },
};
</script>
