<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: null,
      slimFilters: [],
      $input: null
      // basePath: drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix
    }
  },
  computed: {
    ...mapState({
      keys: state => state.Search.keys,
      term: state => state.Search.term,
      filters: state => state.Search.filters
    })
  },
  methods: {
    submit() {
      console.log("search submited", this.typed, this.autocomplete)
      // 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('foreach filters', filter)
        if(filter){
          filters.push(filter)
        }
      })
      console.log('Cleaning filters',this.slimFilters, filters)
      // push router
      this.$router.push({name:'base', query:{
        keys:this.typed,
        term:this.autocomplete,
        filters:filters.join(',')
      }})
      // this.$router.push({
      //   path:`${this.basePath}/base`,
      //   query:{keys:this.typed,term:this.autocomplete}
      // })
    },
    onAutoCompleteSelect(event, ui){
      event.preventDefault();
      console.log('autoCompleteSelect', event, ui)
      this.typed = ui.item.label
      // we have to wait for typed watch to reset autocomplete before setting it
      setTimeout(function(){
        console.log('update autocomplete value after settimeout')
        this.autocomplete = ui.item.value
        if (this.typed !== this.keys || this.autocomplete !== this.term) {
          this.submit()
        }
      }.bind(this), 1)

    },
    onSelectFiltersChange(index, info){
      console.log('onSelectFiltersChange', index, info, this.filters)
      this.slimFilters[index] = info.value
    },
    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('typed changed', o, n)
      // is changed also when autocomplete change it ...
      this.autocomplete = null
    },
    keys(n, o){
      console.log('keys changed', o, n)
      this.typed = n
    },
    term(n, o){
      console.log('autocomplete changed', o, n)
      this.autocomplete = n
    }
  },
  created() {
    this.typed = this.keys
    this.autocomplete = this.term
  },
  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')
    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 = ''
      new SlimSelect({
        select: selectElement,
        placeholder: placeholder,
        // allowDeselect: true
        allowDeselectOption: true,
        showSearch: false,
        closeOnSelect: true,
        onChange: (info) => {
          this.onSelectFiltersChange(index, info)
        }
      })
    })
  },
  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>
