<template>

  <div>
    <div ref="element">
      <slot name="activator" :open="open">
        <div @click.prevent.stop="open">
          <slot :open="open" :hide="hide">
          </slot>
        </div>
      </slot>
    </div>
  </div>

</template>
<style lang="scss">
.itf-editable-element {
  z-index: 1060;
  position: fixed;
}
</style>
<script>
import { Vue, Component, Prop, PropSync } from 'vue-property-decorator';
import itfButton from '../button/Button.vue';
import itfIcon from '../icon/Icon.vue';
import FocusTrap from "bootstrap/js/src/util/focustrap";

export default @Component({
  name: 'itfEditableElement',
  components: {
    itfButton,
    itfIcon,
  }
})
class itfEditableElement extends Vue {
  _backdrop = null;
  _context = null;
  _focusTrap = null;
  _elContainer = null;
  _tempContainer = null;

  isOpen = false;

  async mounted() {
    this._context = this.$el.closest('.itf-append-context:not(.modal-content)') || document.body;

    const { default: Backdrop } = await import('../modal/backdrop');
    this._backdrop = new Backdrop({
      rootElement: this._context,
      isVisible: true,
      isAnimated: true,
      clickCallback: () => {
        this.hide();
      }
    });
    this._focusTrap = new FocusTrap({
      trapElement: this.$el
    });
  }

  open() {
    if (this.isOpen) {
      return;
    }
    this.isOpen = true;

    this.$emit('open');
    this._backdrop.show();
    this._focusTrap.activate();

    this._tempContainer = document.createElement('div');
    this.applyPosition(this._tempContainer, this.$refs.element)
    this._tempContainer.classList.add('itf-editable-element');
    this.$el.removeChild(this.$refs.element);
    this._tempContainer.appendChild(this.$refs.element);
    this._context.appendChild(this._tempContainer);
  }

  applyPosition(container, el) {
    const box = el.getBoundingClientRect();
    const left = box.left + document.body.scrollLeft;
    const top = box.top + document.body.scrollTop;
    container.style.left = `${left}px`;
    container.style.top = `${top}px`;
    container.style.width = `${box.width}px`;
    container.style.height = `${box.height}px`;
    this.$el.style.width = `${box.width}px`;
    this.$el.style.height = `${box.height}px`;
  }

  hide() {
    if (!this.isOpen) {
      return;
    }
    this._focusTrap.deactivate();
    this._backdrop.hide(() => {
      this._tempContainer.removeChild(this.$refs.element);
      this.$el.appendChild(this.$refs.element);
      this._context.removeChild(this._tempContainer); // remove the temporary div

      this.$el.style.width = null;
      this.$el.style.height = null;
      this.isOpen = false;
      this.$emit('hide');
    });
  }

  beforeDestroy() {
    this._backdrop.dispose();
    this._focusTrap.deactivate();
  }
}
</script>
