import { observerDomResize } from '../utils/utils';
import { debounce } from 'canknow-core/src/libs/debounce';

export default {
  data () {
    return {
      dom: '',
      width: 0,
      height: 0,
      debounceInitializeWHFunction: '',
      domObserver: ''
    }
  },
  methods: {
    async autoResizeMixinInitialize () {
      await this.initializeWH(false);
      this.getDebounceInitializeWHFunction();
      this.bindDomResizeCallback();
      if (typeof this.afterAutoResizeMixinInitialize === 'function') this.afterAutoResizeMixinInitialize();
    },
    initializeWH (resize = true) {
      return new Promise(resolve => {
        this.$nextTick(() => {
          this.dom = this.$refs[this.ref];
          this.width = this.dom.clientWidth;
          this.height = this.dom.clientHeight;

          if (typeof this.onResize === 'function' && resize) this.onResize();
          resolve();
        })
      })
    },
    getDebounceInitializeWHFunction () {
      this.debounceInitializeWHFunction = debounce(100, this.initializeWH);
    },
    bindDomResizeCallback () {
      this.domObserver = observerDomResize(this.dom, this.debounceInitializeWHFunction);
      window.addEventListener('resize', this.debounceInitializeWHFunction);
    },
    unbindDomResizeCallback () {
      this.domObserver.disconnect();
      this.domObserver.takeRecords();
      this.domObserver = null;
      window.removeEventListener('resize', this.debounceInitializeWHFunction);
    }
  },
  mounted () {
    this.autoResizeMixinInitialize();
  },
  beforeDestroy () {
    this.unbindDomResizeCallback();
  }
}
