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

    <div>

      <label class="col-form-label" for="selectJob">
        {{ $t('job.label') }}
      </label>

      <VueMultiselect
          name="selectJob"
          label="text"
          :custom-label="customJobLabel"
          track-by="id"
          :multiple="false"
          :searchable="true"
          :placeholder="$t('job.placeholder')"
          v-model="valueJob"
          :options="jobs"
          :select-label="$t('multiselect.select_label')"
          :deselect-label="$t('multiselect.deselect_label')"
          :selected-label="$t('multiselect.selected_label')"
      ></VueMultiselect>

      <label class="col-form-label" for="selectReferrer">
        {{ $t('referrer.label') }}
      </label>

      <VueMultiselect
          name="selectReferrer"
          label="text"
          track-by="id"
          :multiple="false"
          :searchable="true"
          :placeholder="$t('referrer.placeholder')"
          v-model="value"
          :options="users"
          :select-label="$t('multiselect.select_label')"
          :deselect-label="$t('multiselect.deselect_label')"
          :selected-label="$t('multiselect.selected_label')"
      ></VueMultiselect>

      <template v-if="usersSuggestedFilteredByJob.length > 0">
        <ul class="list-suggest add-items inline">
          <li v-for="(u, i) in usersSuggestedFilteredByJob" @click="updateReferrer(u)" :key="`referrer-${i}`">
               <span>
                  <user-render-box-badge :user="u"></user-render-box-badge>
               </span>
          </li>
        </ul>
      </template>
    </div>

    <div>
      <ul class="record_actions">
        <li>
          <button
              class="btn btn-create"
              type="button"
              name="button"
              @click="assignMe">
            {{ $t('referrer.assign_me') }}
          </button>
        </li>
      </ul>
    </div>

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

  </div>
</template>

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

export default {
  name: "Referrer",
  components: {
    UserRenderBoxBadge,
    VueMultiselect,
  },
  data() {
    return {
      jobs: []
    }
  },
  computed: {
    ...mapState({
      valueJob: state => state.accompanyingCourse.job,
    }),
    ...mapGetters(['isJobValid', 'usersSuggestedFilteredByJob']),
    users: function () {
      let users = this.$store.getters.usersFilteredByJob;
      // ensure that the selected user is in the list. add it if necessary
      if (this.$store.state.accompanyingCourse.user !== null && users.find(u => this.$store.state.accompanyingCourse.user.id === u.id) === undefined) {
        users.push(this.$store.state.accompanyingCourse.user);
      }
      return users;
    },
    valueJob: {
      get() {
        return this.$store.state.accompanyingCourse.job;
      },
      set(value) {
        this.$store.dispatch('updateJob', 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'})
              }
            });
      }
    },
    value: {
      get() {
        return this.$store.state.accompanyingCourse.user;
      },
      set(value) {
        console.log('set referrer', value);
        this.$store.dispatch('updateReferrer', 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'})
              }
            });
      }
    },
  },
  mounted() {
    this.getJobs();
  },
  methods: {
    updateReferrer(value) {
      this.value = value;
    },
    getJobs() {
      const url = '/api/1.0/main/user-job.json';
      makeFetch('GET', url)
          .then(response => {
            this.jobs = response.results;
          })
          .catch((error) => {
            this.$toast.open({message: error.txt})
          })
    },
    customJobLabel(value) {
      return value.label.fr;
    },
    assignMe() {
      const url = `/api/1.0/main/whoami.json`;
      makeFetch('GET', url)
          .then(user => {
            this.value = user
          })
      /*.catch((error) => {
         commit('catchError', error);
         this.$toast.open({message: error.body})
      })*/
    }
  }
}
</script>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>
