<script>

import Vue from 'vue'

import router from 'vuejs/route'

import { mapState } from 'vuex'

import SlimSelect from 'slim-select'


export default {
  router,
  props: ['form'],
  data() {
    return {
      template: null,
      typed: null,
      autocomplete: [],
      slimFilters: [],
      $input: null
      // basePath: drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix
    }
  },
  computed: {
    ...mapState({
      keys: state => state.Search.keys,
      terms: state => state.Search.terms,
      filters: state => state.Search.filters
    })
  },
  methods: {
    submit() {
      console.log("slim search submited", this.typed, this.autocomplete, this.filters, this.slimFilters)
      // unfocus the text input to hide the keyboard on mobile device
      this.$input.blur()
      // New search is triggered by Base.vue with router (which will also fill the store)
      // cleaning slimfilters
      let filters = []
      this.slimFilters.forEach((filter, index) => {
        console.log('onsubmit foreach slimFilters', filter)
        if(filter){
          filters.push(filter)
        }
      })
      // // this is just in case we landed in the page with filters in url params, 
      // // this.slimFilters is not filled but store/search filters is
      // if(!filters.length){
      //   filters = this.filters
      // }
      console.log('Cleaning filters',this.slimFilters, this.filters, filters)
      // push router
      this.$router.push({name:'base', query:{
        keys:this.typed,
        // terms:this.autocomplete.join(','),
        terms: JSON.stringify(this.autocomplete),
        filters:filters.join(',')
      }})
    },
    onAutoCompleteSelect(event, ui){
      event.preventDefault();
      console.log('autoCompleteSelect begining', this.typed, event, ui)
      // split typed into tag list
      var tag_list = this.typed.split(', ')
      console.log('tag_list', tag_list)
      // remove the last item as it is the first letters of autocomplete (like ma for marbre)
      tag_list.pop()
      // add in typed the label
      tag_list.push(ui.item.label)

      this.typed = tag_list.join(', ') + ', '

      // check if item is not already in autocmplete 
      let add = true
      this.autocomplete.forEach( (term)  => {
        if (term.value == ui.item.value) {
          add = false
          return
        }
      })
      if (add) {
        this.autocomplete.push(ui.item)
      }
      // we have to wait for typed watch to reset autocomplete before setting it
      // setTimeout(function(){
        // console.log('update autocomplete value after settimeout')
        // this.autocomplete.push(ui.item)
        // if (this.typed !== this.keys || this.autocomplete !== this.term) {
        //   this.submit()
        // }
      // }.bind(this), 1)
     console.log('autoCompleteSelect end : this.autocomplete', this.autocomplete) 

    },
    onSelectFiltersChange(index, info){
      console.log('slim onSelectFiltersChange', index, info, this.slimFilters, this.filters)
      this.slimFilters[index] = info.value
      console.log(this.slimFilters);
      
    },
    onClickFilters(e){
      console.log('onClickFilters legend', e)
      e.target.closest('fieldset').classList.toggle('open')
      // TODO: reset the filters oon close
    }
  },
  directives: {
    focus: {
      // directive definition
      inserted: function (el) {
        // do not focus the input as it popup the keyboard on mobile device
        // el.focus()
      }
    }
  },
  beforeMount() {
    // console.log('SearchForm beforeMount')
    if (this._props.form) {
      // console.log('SearchForm beforeMount if this._props.form ok')
      this.template = Vue.compile(this._props.form)
      // https://github.com/vuejs/vue/issues/9911
      this.$options.staticRenderFns = [];
      this._staticTrees = [];
      this.template.staticRenderFns.map(fn => (this.$options.staticRenderFns.push(fn)));
    }
  },
  watch: {
    typed(n, o){
      console.log(`watch typed changed o:(${typeof o})${o} | n:(${typeof n})${n}`, o, n)
      // if (typeof n === 'string') {
      //   // remove terms from autocomplete if removed from typed
      //   const r = /,\s?$/ // remove last comma space
      //   let tag_list = n.replace(r,'').split(', ')
      // }else{
      //   let tag_list = n
      // }
      // remove terms from autocomplete if removed from typed
      const r = /,\s?$/ // remove last comma space
      let tag_list = n.replace(r,'').split(', ')
      console.log('watch typed tag_list', tag_list)
      console.log('watch typed autocomplete before', this.autocomplete)
      this.autocomplete.forEach( (term,index,array)  => {
        console.log("watch typed autocomplete term", term, index, array)
        if (tag_list.indexOf(term.label) < 0) {
          this.autocomplete.splice(index,1)
        }
      });
      console.log('watch typed autocomplete after', this.autocomplete)
    },
    keys(n, o){
      console.log('watch keys changed', o, n)
      this.typed = n.length ? n.join(', ') + ', ' : ''
    },
    // terms(n, o){
    //   // if term change from store
    //   console.log('watch terms changed', o, n)
    //   this.autocomplete = n
    // }
  },
  created() {
    // fill component values with store values in case of direct page loading
    console.log('SearchForm created, this.keys', this.keys)
    this.typed = this.keys.length ? this.keys.join(', ') + ', ' : ''
    this.autocomplete = this.terms
  },
  mounted(){
    // console.log('SearchForm mounted')
    Drupal.attachBehaviors(this.$el);
    // get the search input
    this.$input = this.$el.querySelector('#edit-search')
    // // focus on input
    // $input.focus()

    // Catch the jquery ui events for autocmplete widget
    jQuery(this.$input).on('autocompleteselect', this.onAutoCompleteSelect);

    // customize the select filters
    // http://slimselectjs.com/options
    const selects = this.$el.querySelectorAll('select')
    console.log('slim selects', selects);
    
    let slim;
    selects.forEach((selectElement, index) => {
      console.log('slim selects forEach', selectElement, index);
      
      // get the first option to make the placeholder then empty it
      const placeholder_option = selectElement.querySelector('option:first-child')
      // console.log('placeholder_option', placeholder_option);
      const placeholder = placeholder_option.innerText
      placeholder_option.removeAttribute("value")
      placeholder_option.setAttribute("data-placeholder", true)
      placeholder_option.innerHTML = ''
      slim = new SlimSelect({
        events:{
          afterChange: (newval) => {
            console.log('slim slimselect onchange', index, newval, this)  
            this.onSelectFiltersChange(index, newval[0])
          }
        },
        select: selectElement,
        placeholder: placeholder,
        allowDeselect: true,
        showSearch: false,
        closeOnSelect: true
      })
      console.log('slim', slim);
      // console.log('slimselect selected', slim, slim.selected(), index)

      this.slimFilters[index] = slim.getSelected()[0];
    })
    console.log('slimSelect slimFilters after init', this.slimFilters)
  },
  render(h) {
    // console.log('searchForm render')
    if (!this.template) {
      return h('span', $t('default.Loading…'))
    } else {
      return this.template.render.call(this)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
