<template>
   <button class="sc-button bt-create centered mt-4" @click="openModal">
      {{ $t(buttonTitle) }}
   </button>

   <teleport to="body">
      <modal v-if="modal.showModal"
         :modalDialogClass="modal.modalDialogClass"
         @close="modal.showModal = false">

         <template v-slot:header>
            <h3 class="modal-title">{{ $t('add_persons.title') }}</h3>
         </template>

         <template v-slot:body-fixed>
            <div class="search">
               <label style="float: right;">
                  {{ $tc('add_persons.suggested_counter', suggestedCounter) }}
               </label>

               <input id="search-persons"
                  name="query"
                  v-model="query"
                  :placeholder="$t('add_persons.search_some_persons')"
                  ref="search" />
               <i class="fa fa-search fa-lg"></i>
            </div>
         </template>

         <template v-slot:body>
            <!--span class="discret">Selection: {{ selected }}</span-->
            <div class="results">
               <div class="count">
                  <span>
                     <a  v-if="suggestedCounter > 0" href="#">
                        {{ $t('action.check_all')}}</a>
                     <a  v-if="selectedCounter > 0" href="#">
                        {{ $t('action.reset')}}</a>
                  </span>
                  <span v-if="selectedCounter > 0">
                     {{ $tc('add_persons.selected_counter', selectedCounter) }}
                  </span>
               </div>

               <person-suggestion
                  v-for="item in this.selectedAndSuggested.slice().reverse()"
                  v-bind:key="item.id"
                  v-bind:item="item"
                  v-bind:search="search"
                  @updateSelected="updateSelected">
               </person-suggestion>

               <button v-if="query.length >= 3" class="sc-button bt-create ml-5 mt-2" name="createPerson">
                  {{ $t('action.create') }} "{{ query }}"
               </button>
            </div>
         </template>

         <template v-slot:footer>
            <button class="sc-button green" 
               @click.prevent="$emit('addNewPersons', { selected, modal })">
               <i class="fa fa-plus fa-fw"></i>{{ $t('action.add')}}
            </button>
         </template>

      </modal>
   </teleport>
</template>

<script>
import Modal from 'ChillMainAssets/vuejs/_components/Modal';
import PersonSuggestion from 'ChillPersonAssets/vuejs/_components/PersonSuggestion';
import { searchPersons } from 'ChillPersonAssets/vuejs/_api/AddPersons';

export default {
   name: 'AddPersons',
   components: {
      Modal,
      PersonSuggestion,
   },
   props: [
      'buttonTitle', 
      'options'
   ],
   emits: ['addNewPersons'],
   data() {
      return {
         modal: {
            showModal: false,
            modalDialogClass: "modal-dialog-scrollable modal-xl"
         },
         search: {
            query: "",
            suggested: [],
            selected: []
         }
      }
   },
   computed: {
      query: {
         set(query) {
            return this.setQuery(query);
         },
         get() {
            return this.search.query;
         }
      },
      suggested() {
         return this.search.suggested;
      },
      suggestedCounter() {
         return this.search.suggested.length;
      },
      selected() {
         return this.search.selected;
      },
      selectedCounter() {
         return this.search.selected.length;
      },
      selectedAndSuggested() {
         const uniqBy = (a, key) => [
               ...new Map(
                  a.map(x => [key(x), x])
               ).values()
         ];
         let union = [...new Set([
            ...this.suggested.slice().reverse(),
            ...this.selected.slice().reverse(), 
         ])];
         return uniqBy(union, k => k.id);
      },
      options() {
         return this.options;
      }
   },
   methods: {
      openModal() {
         this.modal.showModal = true;
         this.$nextTick(function() {
            this.$refs.search.focus();
         })
      },
      setQuery(query) {
         console.log('options 1', this.options);
         this.search.query = query;
         if (query.length >= 3) {
            searchPersons({ query, options: this.options })
               .then(suggested => new Promise((resolve, reject) => {
                  this.loadSuggestions(suggested.results);
                  resolve();
            }));
         } else {
            this.loadSuggestions([]);
         }
      },
      loadSuggestions(suggested) { 
         this.search.suggested = suggested;
      },
      updateSelected(value) {
         this.search.selected = value;
      },
      resetSearch() {
         this.search.selected = [];
         this.search.query = "";
         this.search.suggested = [];
      }
   },
}
</script>
