<script>

import Vue from 'vue'

export default {
  props: ['html'], // get the html from parent with props
  data() {
    return {
      template: null // compiled template from html used in render
    }
  },
  beforeMount() {
    // console.log('Home beforeMount');
    // compile the html src (coming from parent with props or from ajax call)
    if(this.html){
      // console.log('html', this.html);
      this.template = Vue.compile(this.html)
      this.$options.staticRenderFns = []
      this._staticTrees = []
      this.template.staticRenderFns.map(fn => (this.$options.staticRenderFns.push(fn)))
    }
  },
  render(h) {
    if(!this.template){
      return h('span', 'Loading ...')
    }else{
      return this.template.render.call(this)
    }
  },
  mounted(){
    this.initShowroomCarroussel()
  },
  methods: {
    initShowroomCarroussel(){
      console.log("startShowroomCarroussel");
      let $showrooms = document.querySelectorAll('.field--name-computed-showrooms-reference > .field__item')
      console.log('$showrooms', $showrooms);

      // TODO: share media query and variables between scss and js
      let column_width= 205
      let column_goutiere= 13
      let bp = (column_width + column_goutiere )*7 +1
      const mediaQuery = window.matchMedia(`(min-width: ${bp}px)`)
      if (mediaQuery.matches) {
        let $showroomsOdd = []
        let $showroomsEven = []
        for (var i = 0; i < $showrooms.length; i++) {
          if (i%2 === 0) {
            $showroomsOdd.push($showrooms[i])
          }else{
            $showroomsEven.push($showrooms[i])
          }
        }
        console.log('Odd', $showroomsOdd);
        console.log('Even', $showroomsEven);
        this.switchShowroomCarroussel($showroomsEven, 0)
        this.switchShowroomCarroussel($showroomsOdd, 0)
      }else{
        this.switchShowroomCarroussel($showrooms, 0)
      }
    },
    switchShowroomCarroussel($elmts, i){
      // console.log('switchShowroomCarroussel i', $elmts, i);

      $elmts[i].classList.add('active')
      $elmts[i-1 < 0 ? $elmts.length -1 : i-1].classList.remove('active')

      i++
      if(i >= $elmts.length){
        i = 0
      }
      setTimeout(this.switchShowroomCarroussel.bind(this,$elmts,i), 5000);
    },
    onClickLink(e){
      console.log("onClickLink", e, this.$router, this.$route);
      let path = null;
      // find existing router route compared with link href
      for (var i = 0; i < this.$router.options.routes.length; i++) {
        if (this.$router.options.routes[i].path == e.originalTarget.pathname) {
          if (e.originalTarget.pathname !== this.$route.path) {
            path = e.originalTarget.pathname
          }
          break;
        }
      }

      if (path) {
        this.$router.push({
          path: path
        })
      }
    }
  }
}

</script>

<style lang="scss" scoped>
</style>
