<template>
   <div class="vue-component">
      <h2><a id="section-30"></a>{{ $t('origin.title') }}</h2>

      <div class="mb-4">
         <label for="selectOrigin">
            {{ $t('origin.label.fr') }}
         </label>

         <VueMultiselect
            name="selectOrigin"
            label="text"
            :custom-label="transText"
            track-by="id"
            :multiple="false"
            :searchable="true"
            :placeholder="$t('origin.placeholder')"
            v-model="value"
            :options="options"
            @select="updateOrigin">
         </VueMultiselect>
      </div>

      <div v-if="!isOriginValid" class="alert alert-warning to-confirm">
        {{ $t('origin.not_valid') }}
     </div>
   </div>
</template>

<script>
import VueMultiselect from 'vue-multiselect';
import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods';
import { mapState, mapGetters } from 'vuex';

export default {
   name: 'OriginDemand',
   components: { VueMultiselect },
   data() {
      return {
         options: []
      }
   },
   computed: {
      ...mapState({
         value: state => state.accompanyingCourse.origin,
      }),
      ...mapGetters([
         'isOriginValid'
      ])
   },
   mounted() {
      this.getOptions();
   },
   methods: {
      getOptions() {
         const url = `/api/1.0/person/accompanying-period/origin.json`;
         makeFetch('GET', url)
            .then(response => {
               this.options = response.results;
               return response;
            })
            .catch((error) => {
               commit('catchError', error);
               this.$toast.open({message: error.txt})
            })
      },
      updateOrigin(value) {
         this.$store.dispatch('updateOrigin', value)
            .catch(({name, violations}) => {
               if (name === 'ValidationException' || name === 'AccessException') {
                  violations.forEach((violation) => this.$toast.open({message: violation}));
               } else {
                  this.$toast.open({message: 'An error occurred'})
               }
            });
      },
      transText ({ text }) {
         return text.fr;
      },
   }
}
</script>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>
<style lang="css" scoped>
   label {
      display: none;
   }
</style>
