<script>

import Vue from 'vue'

import router from 'vuejs/route'

import { mapState } from 'vuex'

export default {
  router,
  props: ['form'],
  data() {
    return {
      template: null,
      typed: null,
      autocomplete: null,
      // basePath: drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix
    }
  },
  computed: {
    ...mapState({
      keys: state => state.Search.keys,
      term: state => state.Search.term
    })
  },
  methods: {
    submit() {
      console.log("search clicked", this.typed, this.autocomplete);
      // New search is triggered by Base.vue with router (which will also fill the store)
      this.$router.push({name:'base', query:{keys:this.typed,term:this.autocomplete}})
      // 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
      this.autocomplete = ui.item.value
    }
  },
  directives: {
    focus: {
      // directive definition
      inserted: function (el) {
        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: {
    keys(n, o){
      console.log('keys changed', n, o);
      this.typed = n
    },
    term(n, o){
      console.log('autocomplete changed', n, o);
      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
    let $input = this.$el.querySelector('#edit-search')
    // // focus on input
    // $input.focus()
    // Catch the jquery ui events for autocmplete widget
    jQuery($input).on('autocompleteselect', this.onAutoCompleteSelect);
  },
  render(h) {
    // console.log('searchForm render');
    if(!this.template){
      return h('span', 'Loading ...')
    }else{
      return this.template.render.call(this)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
